Output to Standard Output

The print operator takes a list of values and sends each item (as a string, of course) to standard output in turn, one after another. It doesn’t add any extra characters before, after, or in between the items;[*] if you want spaces between items and a newline at the end, you have to say so:

$name = "Larry Wall";
print "Hello there, $name, did you know that 3+4 is ", 3+4, "?\n";

Of course, that means that there’s a difference between printing an array and interpolating an array:

print @array;     # print a list of items
print "@array";   # print a string (containing an interpolated array)

That first print statement will print a list of items, one after another, with no spaces in between. The second one will print exactly one item, which is the string you get by interpolating @array into the empty string—that is, it prints the contents of @array, separated by spaces.[] So, if @array holds qw/ fred barney betty /,[] the first one prints fredbarneybetty, while the second prints fred barney betty separated by spaces.

But before you decide to always use the second form, imagine that @array is a list of unchomped lines of input. That is, imagine that each of its strings has a trailing newline character. Now, the first print statement prints fred, barney, and betty on three separate lines. But the second one prints this:

 fred
  barney
  betty

Do you see where the spaces come from? Perl is interpolating an array, so it puts spaces between the elements. So, we get the first element ...

Get Learning Perl, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.