Table of Contents

Print: A List Operator

The 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 print function in list context
is that expressions are evaluated before being printed. For example, try this: 
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 $var ? 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 it.

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 function, then 1 was added. You can prove this to yourself by adding the line print "\$var is now $var\n"; to the end of the example above.

If we want the operation to be performed on $var before the value is returned to the print function, then preincrement is the way to go. ++$var will do the trick.