What is the easiest way to print all a list's elements separated by line feeds in Perl?
This won't print a newline at the end, which isn't bad on Windows but will look ugly on *nix systems.
Chris Lutz
2009-12-08 01:16:51
And? The question specifically says *separated by*.
Andrew Medico
2009-12-08 01:17:53
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
2009-12-08 01:24:32
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
2009-12-08 21:57:03
Sorry about that - I've been working in environments where single quotes indicate a character. Fixed now.
Anon.
2009-12-08 22:59:32
+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
2009-12-08 01:16:22
I tend to add a dummy element at the end of the list: `print join("\n", @list, '')`
Michael Carman
2009-12-08 01:45:28
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
2009-12-08 01:50:03
+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
2009-12-08 01:30:38
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
2009-12-08 01:42:05