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.[125] 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 printing an array and interpolating an array are different:

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

The first print statement will print a list of items, one after another, with no spaces in between. The second one will print 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.[126] If @array holds qw/ fred barney betty /,[127] the first one will print fredbarneybetty, and the second will print fred barney betty separated by spaces.

But before you decide to use the second form all the time, 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. We get the first element of the array ...

Get Learning Perl, Fourth 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.