Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

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

by pemungkah (Priest)
on Jan 09, 2014 at 01:18 UTC ( #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? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2022-05-25 17:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (90 votes). Check out past polls.

    Notices?