Lanbo
Lanbo

Reputation: 15692

Sub writing and string concatenation

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.

Upvotes: 3

Views: 322

Answers (1)

Ed Guiness
Ed Guiness

Reputation: 35267

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;
}

Upvotes: 7

Related Questions