Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re^2: Warning while using ternary operator

by kcott (Abbot)
on Dec 16, 2013 at 15:19 UTC ( #1067344=note: print w/ replies, xml ) Need Help??


in reply to Re: Warning while using ternary operator
in thread Warning while using ternary operator

This is bad information.

The expression

$expression ? $var = "foo" : $var = "bar";

is only "# WRONG" because of operator precedence (see perlop: Operator Precedence and Associativity). Here's how it is parsed:

$ perl -MO=Deparse,-p -e '$expression ? $var = "foo" : $var = "bar";' (($expression ? ($var = 'foo') : $var) = 'bar'); -e syntax OK

This is explained in perlop: Conditional Operator. Correcting the precedence with parentheses:

$ perl -MO=Deparse,-p -e '$expression ? ($var = "foo") : ($var = "bar" +);' ($expression ? ($var = 'foo') : ($var = 'bar')); -e syntax OK

I do not dispute that '$var = $expression ? "foo" : "bar";' is a better way to write '$expression ? ($var = "foo") : ($var = "bar");'. In fact, the documentation also recommends this.

Once corrected as indicated, here's how your "# WRONG" code behaves:

#!/usr/bin/env perl -l use strict; use warnings; for my $expression (0, 1) { my $var = ''; $expression ? ($var = 'foo') : ($var = 'bar'); print "\$expression = '$expression'; \$var = '$var'"; }

Output:

$expression = '0'; $var = 'bar' $expression = '1'; $var = 'foo'

-- Ken


Comment on Re^2: Warning while using ternary operator
Select or Download Code
Re^3: Warning while using ternary operator
by AnomalousMonk (Abbot) on Dec 16, 2013 at 23:15 UTC

    But what does the syntactically correct statement
        $expression ? $var = "foo" : $var = "bar";
    actually do?

    >perl -wMstrict -le "for my $expression (0, 1) { my $var = ''; $expression ? $var = 'foo' : $var = 'bar'; print qq{if \$expression is $expression, \$var is '$var'} } " if $expression is 0, $var is 'bar' if $expression is 1, $var is 'bar'

    It seems the statement is just an expensive equivalent to the statement
        $var = 'bar';
    The reason why is left as a exercise for simonz (after the recommended perusal of perlop :)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2015-07-04 21:30 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 (60 votes), past polls