[Israel.pm] RE: 2 Qs on assignment and evaluation

Offer Kaye oferk at oren.co.il
Thu Jan 29 02:28:57 PST 2004

> The following snippet:
> __perl code starts__
> #!/usr/local/bin/perl -w
> use strict;
> use diagnostics;
> my $res = my $a = 3;
> print "\nres is $res.\n";
> print $a=2, $a++, "\n";
> _perl code ends____
> produces:
> __perl output starts__
> res is 3.
> 32
> __perl output ends___
> Q1. Shouldn't $res have the value of the _assignment operation_
> (usually 1,I
> guess) and not the value which $a is assigned to?

No, it returns the value it assigned, see perldoc perlop:
Unlike in C, the scalar assignment operator produces a valid lvalue...
Similarly, a list assignment in list context produces the list of lvalues
assigned to...

> Q2. Shouldn't the second print produce 23 instead of 32?

A bit tricky. Again, the answer is in perlop:
"++" and "--" work as in C.  That is, if placed before a variable, they
increment or decrement the variable before returning the value, and if
placed after, increment or decrement the variable after returning the

So consider what happened- for print to work, it first has to evaluate the
list of arguments.
The first, "$a=2", does just what you expect, setting $a to 2.
The next, $a++, *first* returns 2, *then* increases $a to 3.
Finally, "\n" is "\n", so print is finished. However, $a was changed, so the
final output is:
Which is what you got. QED :-)

Offer Kaye

More information about the Perl mailing list