Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

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

by Eily (Curate)
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
Replies are listed 'Best First'.
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 drinking their drinks and smoking their pipes about the Monastery: (10)
As of 2015-07-08 02:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (93 votes), past polls