tags:

views:

122

answers:

3

What is the easiest way to print all a list's elements separated by line feeds in Perl?

+6  A: 
print join "\n", @list;
Anon.
This won't print a newline at the end, which isn't bad on Windows but will look ugly on *nix systems.
Chris Lutz
And? The question specifically says *separated by*.
Andrew Medico
Most people want newlines printed at the ends of the things they print. That's why most languages provide a function that do exactly that. Even C does it with `puts()`.
Chris Lutz
You need to put the \n in double quotes to have it interpreted as line-feed. In single quotes you'll get the two characters backslash and n.
asjo
Sorry about that - I've been working in environments where single quotes indicate a character. Fixed now.
Anon.
+13  A: 
print "$_\n" for @list;

In Perl 5.10:

say for @list;

Another way:

print join("\n", @list), "\n";

Or (5.10):

say join "\n", @list;

Or how about:

print map { "$_\n" } @list;
Chris Lutz
I tend to add a dummy element at the end of the list: `print join("\n", @list, '')`
Michael Carman
That works for this case, but not so well if you want to join it with something other than newlines (which I occasionally do), and if you change your mind on how you want the output format to look, doing that just makes it take a little extra work.
Chris Lutz
+5  A: 

Why not abuse Perl's global variables instead

local $\ = "\n";
local $, = "\n";
print @array;

If you get excited for unnecessary variable interpolation feel free to use this version instead:

local $" = "\n";
print "@array\n";
jonchang
Of course, we _could_ just make this global variable abuse safe and sanitary: `sub arrprint (\@;$$) { my @a = @{shift()}; local $\ = @_ ? shift : $\; local $, = @_ ? shift : $,; print @$aref; }` (code untested)
Chris Lutz