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

Re: Boolean counter?

by Corion (Pope)
on Dec 07, 2009 at 08:06 UTC ( #811442=note: print w/ replies, xml ) Need Help??


in reply to Boolean counter?

The xor operator will do what you want:

$counter = $counter xor 1

or

$counter ^= 1

(tested with perl -wle "print $counter ^=1 for 1..3")


Comment on Re: Boolean counter?
Select or Download Code
Replies are listed 'Best First'.
Re^2: Boolean counter?
by doug (Pilgrim) on Dec 07, 2009 at 18:22 UTC

    I agree that the XOR solution is perfectly correct, but why use that instead of NOT? Isn't

     $counter = ! $counter;

    easier to read? That said, I have to admit that I like the snazzyness of the in place ^= syntax. It is hard to get more concise than that.

    - doug

      The difference is that $toggle ^= 1; leaves you with a number (0 or 1) while $toggle = !$toggle; leaves you with a boolean.

      Honestly, it sounds like the OP wants a boolean, so the easier to read negation should be used. If he wants to display the boolean, that's an outputting formatting issue to be resolved then.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (8)
As of 2015-07-31 02:23 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 (274 votes), past polls