Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: strange output from conditional operator

by moritz (Cardinal)
on May 15, 2009 at 11:43 UTC ( [id://764250]=note: print w/replies, xml ) Need Help??


in reply to strange output from conditional operator

You were bitten by the fact that the ternary operator ? : has a tighter precedence than the assignment operator. Instead, try this:
$var .= (defined($var) ? 'y' : 'n';

See also Confused by Perl ternary operator, perlop.

Replies are listed 'Best First'.
Re^2: strange output from conditional operator
by december (Pilgrim) on May 15, 2009 at 12:23 UTC

    Yes that works – I knew it does – but I was wondering why doing it this way caused such strange output...

    I've given thought to operator precedence, but I figured things wouldn't align up and I'd get a warning or error.

    So how would this get parsed? Something like the following I presume:

    (defined($var) ? $var) .= ('y' : $var .= 'n') if $el eq 'apple';

    Thanks for the explanation, operator precedence makes a lot more sense now. I'm just surprised things lined up well enough not to cause any warnings or syntax errors.

      The thread I've linked to above has an example both for how something very similar gets parsed, and how to find out how it's parsed. Did you not read it?
      (defined($var) ? $var) .= ('y' : $var .= 'n') if $el eq 'apple';
      No, because there can be no ? without an accompanying :. Thus, the ‘middle’ assignment is parsed as you like (since the tokeniser hasn't seen a : yet, hence knows that it's still inside the conditional), but the ‘last’ one isn't (since the tokeniser believes it's done with the conditional after finding the second occurrence of $var):
      (defined($var) ? $var .= 'y' : $var) .= 'n'

      (Of course, the statement about every ? requiring an accompanying : is a lie, as regular expressions show; but you know what I mean. :-) )

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (3)
As of 2024-04-19 01:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found