Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

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

by Eily (Hermit)
on Mar 04, 2014 at 22:27 UTC ( #1076988=note: print w/ replies, xml ) Need Help??


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?


Comment on Re: Why does the first $c evaluate to the incremented value in [$c, $c += $_] ?
Select or Download Code
Re^2: Why does the first $c evaluate to the incremented value in [$c, $c += $_] ?
by linuxer (Deacon) 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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1076988]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (13)
As of 2014-07-23 18:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (150 votes), past polls