Print: A List Operator
print function is a list operator.
That means it accepts a list of things to print, separated by commas. As an example:
print "a doublequoted string ", $var, 'that was a variable called var', $num," and a newline \n";
Of course, you just put all the above inside a single doublequoted string:
print "a doublequoted string $var that was a variable called var $num and a newline \n";
to achieve the same effect. The advantage of using the
$var="Perl"; $num=10; print "Two \$nums are $num * 2 and adding one to \$var makes $var++\n"; print "Two \$nums are ", $num * 2," and adding one to \$var makes ", $var++,"\n";
You might have been slightly surprised by the result of that last experiment. In
particular, what happened to our variable
It should have been incremented by one, resulting in
Perm. The reason being
that 'm' is the next letter after 'l' :-)
Actually, it was incremented by 1. We are postincrementing
$var++ the variable, rather than preincrementing
The difference is that with postincrements, the value of the variable is returned, then
the operation is performed on it. So in the example above, the current value of
$var was returned to the
print "\$var is now $var\n"; to
the end of the example above.
If we want the operation to be performed on
before the value is returned to the print function, then preincrement is the way to go.
++$var will do the trick.