fergal has asked for the wisdom of the Perl Monks concerning the following question:

for (1..10) { $first ||= $last = $_; } print "$first..$last\n";

I was doing something like this in a one liner (to extract the first and last lines of a file). It made me scratch my head.

Is this a feature? (this is the meditation part of the posting :).

Update: I know why it does it, I'm just curious to see if anyone else is surprised by it or gets it wrong first time.

Replies are listed 'Best First'.
Re: what does this print?
by cog (Parson) on Apr 28, 2005 at 16:35 UTC
    I know the result of that looks absurd at first, but there's a reason, in fact :-)

    You're looking at $first ||= $last = $_; and mentally comparing it to $first = $last = $_;

    The problem is: you should compare it to $first = $first || ($last = $_)

    Being a short-circuit operator, ||= doesn't get it's right-hand side to be evaluated unless necessary :-)

Re: what does this print?
by eric256 (Parson) on Apr 28, 2005 at 16:54 UTC

    The short cuting of the ||= is throwing you off. The right hand side doesn't get evaluated if $first is defined.

    for (1..10) { $last = $_; $first ||= $last; } print "$first..$last\n";
    Prints as expected. cog beat me to it, thats what i get for not refreshing the node before replying. ;)

    ___________
    Eric Hodges
Re: what does this print?
by salva (Canon) on Apr 28, 2005 at 16:31 UTC
    "1..1"?

    What did you expected? your code is equivalent to...

    for (1..10) { unless ($first) { $last = $_; $first = $last; } } print "$first..$last\n";