http://www.perlmonks.org?node_id=1076988


in reply to Why does the first $c evaluate to the incremented value in [$c, $c += $_] ?

This raises another question though: this is fairly simple and understandable (and in this case, Perl doesn't DWIM), how should it be written instead?

$c_old = $c; $c+=$_; [$c_old, $c]; is quite cumbersome. ($c = $c_old = $c) += $_; is just messing with peoples' head;. So I thought "Well, the unary + has a high precedence, and it's actually just the identity operator, this should work just fine":

perl -MData::Dumper -E 'say join ", ", +$c,$c+=1 for 1..3'

1, 1 2, 2 3, 3
I thought I had missed something, but because I did have an idea of what was happening I thought "well, I'll just try it with two - instead"

perl -MData::Dumper -E 'say join ", ", --$c,$c+=1 for 1..3'

0, 0 0, 0 0, 0
Yup, stupid, -- is not two unary -, but one auto-decrement operator. So:

perl -MData::Dumper -E 'say join ", ", - -$c,$c+=1 for 1..3'

0, 1 1, 2 2, 3
Talking about clear code ... So I guess hazylife's version is actually the best: $c+0,$c+=$_; with a comment at the end so that the next person reading the code does not think "Oh, +0, now that's silly, let's just remove it!"

But still, +$c should work shouldn't it? What happens is obvious, perl just "optmises" it away as soon as it sees it. That's still an inconsistency, because you can't just replace a unary - with a unary + and expect the things to happen in the same order. I could only try that in perl v5.14, but I suppose it's still the case in later versions, could someone try it?

Replies are listed 'Best First'.
Re^2: Why does the first $c evaluate to the incremented value in [$c, $c += $_] ?
by linuxer (Curate) on Mar 04, 2014 at 23:18 UTC

    Looks the same here, with Perl 5.18.1 on Linux:

    perl -MData::Dumper -E 'say join ", ", +$c,$c+=1 for 1..3'

    1, 1 2, 2 3, 3

    perl -MData::Dumper -E 'say join ", ", --$c,$c+=1 for 1..3'

    0, 0 0, 0 0, 0

    perl -MData::Dumper -E 'say join ", ", - -$c,$c+=1 for 1..3'

    0, 1 1, 2 2, 3