Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: return value of "if" (documentation?)

by pemungkah (Priest)
on Jan 09, 2014 at 01:18 UTC ( [id://1069892]=note: print w/replies, xml ) Need Help??


in reply to return value of "if" (documentation?)

For your construction, I'd recommend a chained ternary expression:
print "$_ is ", $_ == 0 ? 'zero' : $_ > 0 ? 'pos' : 'neg', "\n" for -1..1;
The ternary operator ?: is essentially an if statement designed to return a value in a guaranteed-defined way. Breaking this down:
  • $_ == 0 ? 'zero' : ... does 'this is zero or something else'
  • $_ > 0 ? 'pos' : 'neg' does the 'something else': positive or negative
I've inserted the line breaks in this particular way to make it easy to see how the chain of logical expressions is evaluated. This also makes it easy to see where to edit new tests in:
print "$_ is ", $_ == 0 ? 'zero' : $_ == 2 ? 'two' : $_ == -1 ? 'minus one' : $_ > 0 ? 'pos' : 'neg', "\n" for -2..2;

Log In?
Username:
Password:

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

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

      No recent polls found