Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Re: Multiple if-else statements using C-style ternary operator

by spazm (Monk)
on Jul 11, 2011 at 22:46 UTC ( #913795=note: print w/replies, xml ) Need Help??

in reply to Multiple if-else statements using C-style ternary operator

my $message = $status == 2 ? 'HIGH' : $status == 1 ? 'MODERATE' : 'LOW' print $message

Depending on the depth of status, you may want to use a hash

my %status_message = { 2 => 'HIGH', 1=>'MODERATE', 0=>'LOW' }; my $message = $status_message{ $status } || 'LOW';
Or even a standard array if the values really are ints in a 0..n range.
my @status_messages = qw( LOW MODERAGE HIGH ); my $message = $status_messages[$status] || 'LOW';
These are both made a little more odd by the the inclusiveness of the default "LOW" value. Your demo code makes message "LOW" for any status other than 1 or 2.

Replies are listed 'Best First'.
Re^2: Multiple if-else statements using C-style ternary operator
by JavaFan (Canon) on Jul 11, 2011 at 23:04 UTC
    my %status_message = { 2 => 'HIGH', 1=>'MODERATE', 0=>'LOW' };
    That's not what you want. That creates a hash with a key of the form "HASH(0xDEADBEEF)", and an undefined value has the value.

    Perhaps you intended to write paren instead?

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://913795]
[holli]: i'd like to keep my sanity, tyvm
[holli]: at least what's left off it :)
[LanX]: the+everything+ bible
[LanX]: http://web.archive .org/web/ 20071005212040/ http://www. Everything %20Diagram
erix .oO( hm, tough beans )

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (9)
As of 2017-11-20 21:47 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (294 votes). Check out past polls.