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 of the array (fred and a newline
character), then a space, then the next element of the array
(barney and a newline character), then a space,
then the last element of the array (betty and a
newline character). The result is that the lines seem to have become
indented, except for the first one. Every week or two, a message
appears on the newsgroup comp.lang.perl.misc
with a subject line something like:
Perl indents everything after the first line
But if you (or a program) may be waiting impatiently for the output,
you may wish to take that performance hit and flush the output buffer
each time you print. See the Perl manpages for
more information on controlling buffering in that case.
Since print is looking for a list of strings to
print, its arguments are evaluated in list context. Since the diamond
operator (as a special kind of line-input operator) will return a
list of lines in a list context, these can work well together:
print <>; # source code for 'cat'
print sort <>; # source code for 'sort'
$result = print("hello world!\n");
But what if you used the result in some other way? Let's
suppose you decide to multiply the return value times four:
print (2+3)*4; # Oops!
When Perl sees this line of code, it prints 5,
just as you asked. Then it takes the return value from
print, which is 1, and
multiplies that times 4. It then throws away the
product, wondering why you didn't tell it to do something else
with it. And at this point, someone looking over your shoulder says,
"Hey, Perl can't do math! That should have printed
20, rather than 5!"
This is the problem with allowing the parentheses to be optional;
sometimes we humans forget where the parentheses really belong. When
there are no parentheses, print is a list
operator, printing all of the items in the following list;
that's generally what you'd expect. But when the first
thing after print is a left parenthesis,
print is a function call, and it will print only
what's found inside the parentheses. Since that line had
parentheses, it's the same to Perl as if you'd said this:
( print(2+3) ) * 4; # Oops!
Fortunately, Perl itself can almost always help you with this, if you
ask for warnings -- so use -w, at least during
program development and debugging.