|Welcome to the Monastery|
Re: Why does the first $c evaluate to the incremented value in [$c, $c += $_] ?by Eily (Prior)
|on Mar 04, 2014 at 22:27 UTC||Need Help??|
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'
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'
Yup, stupid, -- is not two unary -, but one auto-decrement operator. So:
perl -MData::Dumper -E 'say join ", ", - -$c,$c+=1 for 1..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?