Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sub writing and string concatenation

Tags:

perl

Good day,

For work I am suddenly required to know Perl, and though I have dabbled in those arts years ago, I seem to be completely lost. For a Haskell/Java programmer, all these unstructured typing can get on the nerves.

However, I wrote this sub that is supposed to take an array of single-line strings and concatenate them to a single, multi-lined strings. I had it Like so:

sub unlines {
    my ( @lines ) = @_;
    my $str = "";
    foreach $line ( @lines ) {
        $str = join $str, chomp($line), "\n";
    }
    return $str;
}

And then I wanted to test it, of course:

print unlines(("GET / http1.1", "Host: localhost", ""));

And the result of the thing is

000

And a lot of newlines. I have absolutely no idea why that is. Anyone can help me and explain, perhaps, how all these argument passing to subs in Perl works? It seems to be very interesting to work with things like @_ and shift, but the typing... it's a nightmare.

Thanks for listening.

like image 272
Lanbo Avatar asked Mar 10 '26 00:03

Lanbo


1 Answers

Your trouble lies in how chomp works; it doesn't return the chomped variable, it returns the number of characters removed and alters the variable in-place.

So chomp first and join later, like this...

C:\temp>cat test.pl
my @lines = ('abc','def');
chomp @lines;
print join "\n",@lines;

C:\temp>test.pl
abc
def
C:\temp>

And for completeness, here's how your unlines() could look

sub unlines {
    my @lines = @_;
    chomp @lines;    
    return join "\n", @lines;
}
like image 130
Ed Guiness Avatar answered Mar 12 '26 17:03

Ed Guiness



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!