Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: ternary operator

by GrandFather (Saint)
on Jul 17, 2006 at 22:36 UTC ( [id://561877]=note: print w/replies, xml ) Need Help??


in reply to ternary operator

There may be a Perl bug here. Because of operator precedence I'd have expected that the trinary experession shouldn't compile. The assignment operator has lower percedence than the trinary operator.

However the immediate answer to your problem is to fix the precedence issue. Here are two fixes:

1/ $test ne 'c' ? ($OPER='s') : ($OPER='c'); 2/ $OPER = $test ne 'c' ? 's' : 'c';

DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: ternary operator
by japhy (Canon) on Jul 17, 2006 at 22:55 UTC
    No bug. The statement parses as ($test ne 'c' ? ($OPER = 's') : $OPER) = 'c';

    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart

      which to me looks like:

      $OPER = 's' = 'c';

      when $test ne 'c' is true. And that should fail with a "Can't modify constant item in scalar assignment" error. However no errors and no warnings are generated for either condition.

      Using ?: to select a variable to be assigned to I'm happy with:

      test ? $p1 : $p2 = value;

      but the half assignement variant implied by the precedence (and made explicit by the brackets shown in your reply) is just bizare.


      DWIM is Perl's answer to Gödel

        which to me looks like: $OPER = 's' = 'c'; when $test ne 'c' is true. And that should fail with a "Can't modify constant item in scalar assignment" error.

        You're forgetting the precedence -- or should I say associativity? -- no, I think precedence is correct here. It is actually like ($OPER = 's') = 'c', which, while admittedly bizarre, is perfectly legal, since $OPER = 's' evaluates to an lvalue $OPER. Observe the difference:

        sidhekin@blackbox:~$ perl -le '($c = 1) = 2; print $c' 2 sidhekin@blackbox:~$ perl -le '$c = 1 = 2; print $c' Can't modify constant item in scalar assignment at -e line 1, near "2; +" Execution of -e aborted due to compilation errors. sidhekin@blackbox:~$

        print "Just another Perl ${\(trickster and hacker)},"
        The Sidhekin proves Sidhe did it!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2024-04-23 11:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found