Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re^2: Boolean counter?

by shawnhcorey (Pilgrim)
on Dec 07, 2009 at 14:07 UTC ( #811504=note: print w/ replies, xml ) Need Help??

in reply to Re: Boolean counter?
in thread Boolean counter?

$Counter = - --$Counter;

Comment on Re^2: Boolean counter?
Download Code
Re^3: Boolean counter?
by JavaFan (Canon) on Dec 07, 2009 at 15:13 UTC
    The behaviour of that is actually not defined. You may end up with $Counter being -1, or with purple daemons coming out of your USB port, ready to chew off your fingers.
      What about it is not defined?

        duh, you're referring to the fact that he's assigning to the variable he just modified. I was still asleep.

        While such constructs should be avoided over clarity concerns, it's wrong to say it's undefined. The precedence and evaluation order for that statement is actually clearly defined in perlop.

      $i appears only once, the behaviour is defined
      $ perl -MO=Deparse,-p -le"print - --$i" BEGIN { $/ = "\n"; $\ = "\n"; } print((-(--$i))); -e syntax OK
      You were thinking of
      print(-( ++$i - --$i ))

        While the operand evaluation order for the ops you've used in your example isn't defined, it doesn't matter (unless there's an overflow) for that example. It's just a clarity issue.

        $i appears only once, the behaviour is defined

        Except it ($Counter) appeared twice.

Re^3: Boolean counter?
by ikegami (Pope) on Dec 07, 2009 at 17:08 UTC

    Don't modify a variable that you're using elsewhere in an expression. At best, it's unclear. At worse, the result is undefined.

    $toggle = - --$toggle;
    should be
    $toggle = -( $toggle - 1 );
    which can be shortened to previously mentioned
    $toggle = 1 - $toggle;

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (13)
As of 2015-03-28 13:20 GMT
Find Nodes?
    Voting Booth?

    When putting a smiley right before a closing parenthesis, do you:

    Results (625 votes), past polls