in reply to Friday Code Quiz

There have already been some correct answers in the thread, but here's a full explanation.

Stage 1: People who run the code see that $i is set to 1. They then try to come up with an explanation. One common one I've seen is that they claim that the comma operator returns its left operand in scalar context. This gives them the right answer, but for the wrong reason.

Stage 2: Other people realise that the comma operator returns its rightoperand in scalar context. This means that $i should be set to 2. This makes sense, but is disproved by the evidence.

Stege 3: Finally, we reach for the precedence table and realise that Perl is parsing the expression as ($i=1),2;.

It's worth pointing out that -w gives a helpful warning, but also that B::Deparse is a useful tool in investigating weirdness like this:

perl -MO=Deparse -e'$i=1,2'
--
<http://www.dave.org.uk>

"The first rule of Perl club is you don't talk about Perl club."

Replies are listed 'Best First'.
Re: Re: Friday Code Quiz
by spudzeppelin (Pilgrim) on Sep 21, 2001 at 20:00 UTC

    As evidenced by the output of the following one-liner:

    perl -e 'sub bob { $i=1,2;} print $i, "\t", scalar bob, "\n";'

    If I've learned one thing about interpreting obfu, it's that if I can't immediately tell what a line of code does, make it a subroutine and observe its behavior in isolation.

    Spud Zeppelin * spud@spudzeppelin.com

Re: Re: Friday Code Quiz
by runrig (Abbot) on Sep 21, 2001 at 20:16 UTC
    Though I usually don't have useless constants in a void context, I might use that sort of construct for loop control (among other things) if you want something else to happen before the control statement, and you don't want to waste space on a whole 'if' block, e.g.:
    $success = 1, last if something(); # And I know TMTOWTDI but you get the idea $success = something() and last; last if $success = something();