Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: "x ? y : z" notation

by Old_Gray_Bear (Bishop)
on Mar 26, 2009 at 00:32 UTC ( [id://753302]=note: print w/replies, xml ) Need Help??


in reply to "x ? y : z" notation

It's called the 'conditional' or 'ternary' operator.
<condition> ? <do if condition was true> : <do if it wasn't>
An example:
$x == 1 ? print "x was '1'" : print "x was something else";

----
I Go Back to Sleep, Now.

OGB

Replies are listed 'Best First'.
Re^2: "x ? y : z" notation
by davido (Cardinal) on Mar 26, 2009 at 04:58 UTC
    $x == 1 ? print "x was '1'" : print "x was something else";

    While that's technically correct it doesn't take advantage of the fact that the ternary operator has a return value; whatever expression is evaluate after the ?.

    See another adaptation that takes advantage of this feature.

    print( "x was " . $x == 1 ? "'1'" : "someting else" );

    Dave

      take advantage of the fact that the ternary operator has a return value
      How true; Perl is a bit unorthogonal in this respect, in that there is (at least) one case where you can achieve this effect with a plain 'if':

      sub lessthan { if($_[0] < $_[1]) {1} else {0} }
      Some languages (old examples: Algol60 and Algol68) are more regular in this respect...

      BTW, does someone know by chance which was the first language which used ?: to represent "ternary if"? Of course you had this already in LISP or BCPL, but with a different syntax. The earliest occurance of ?: I know of, is in C, but I wouldn't be surprised if it was used in even older languages already.

      -- 
      Ronald Fischer <ynnor@mm.st>
Re^2: "x ? y : z" notation
by apok (Acolyte) on Mar 26, 2009 at 00:38 UTC
    Thanks for the explanation! I thought it might be something like that.

    -----
    "Ask not what you can do for your country. Ask what's for lunch."
    -- Orson Welles

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2024-04-18 20:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found