Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Question about ternary condition

by robartes (Priest)
on Jun 28, 2005 at 09:45 UTC ( #470546=note: print w/ replies, xml ) Need Help??


in reply to Question about ternary condition

You're being bitten by precedence. Ternary ?: has a higher precedence than =, so what perl parses is:

Y:\tmp>perl -MO=Deparse,-p 470538.pl (my(%hash) = ('A', 'on', 'B', 'on', 'C', 'off', 'D', 'off', 'E', 'off' +)); foreach $_ (keys(%hash)) { my($result); (((exists($hash{$_}) && ($hash{$_} eq 'on')) ? ($result = 'OK') : +$result) = 'KO'); print($result, "\n"); } 470538.pl syntax OK

You're effectively doing ($result='OK')='KO' in the case of a match, hence your output. The solution is of course to use parentheses:

(exists $hash{$_} and $hash{$_} eq 'on') ? ($result = 'OK') : ($result = 'KO');

Nice gotcha you found there :)

CU
Robartes-


Comment on Re: Question about ternary condition
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (7)
As of 2014-12-25 14:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (160 votes), past polls