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

Re: ternary conditional help

by AnomalousMonk (Archbishop)
on Nov 29, 2016 at 00:25 UTC ( [id://1176758]=note: print w/replies, xml ) Need Help??


in reply to ternary conditional help

In addition to the deparse examples provided by haukex here, consider the OPed code and a slight modification. In the first, original version, constant folding (I think that's the correct phrase) makes the ternary go away and reduces the expression to a pure assignment (albeit a two-step one):

c:\@Work\Perl\monks>perl -wMstrict -MO=Deparse,-p -le "my $a = 'a'; my $b = 'b'; 1 ? $a = 2 : $b = 'x'; print qq{a is $a}; print qq{b is $b}; " BEGIN { $^W = 1; } BEGIN { $/ = "\n"; $\ = "\n"; } use strict 'refs'; (my $a = 'a'); (my $b = 'b'); (($a = 2) = 'x'); print("a is $a"); print("b is $b"); -e syntax OK
Making the condition expression of the ternary non-constant preserves the ternary operator in all its LHS glory:
c:\@Work\Perl\monks>perl -wMstrict -MO=Deparse,-p -le "my $a = 'a'; my $b = 'b'; my $p = 1; $p ? $a = 2 : $b = 'x'; print qq{a is $a}; print qq{b is $b}; " BEGIN { $^W = 1; } BEGIN { $/ = "\n"; $\ = "\n"; } use strict 'refs'; (my $a = 'a'); (my $b = 'b'); (my $p = 1); (($p ? ($a = 2) : $b) = 'x'); print("a is $a"); print("b is $b"); -e syntax OK
Please see O and B::Deparse.


Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2024-04-20 02:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found