http://www.perlmonks.org?node_id=913788

gansvv has asked for the wisdom of the Perl Monks concerning the following question:

How do I compose multiple if-else statements using the C-style ternary operator?

Say, $status can have the following values:
2 meaning "HIGH",
1 meaning "MODERATE", or
0 meaning "LOW".
How can I concisely code to print the message given the $status variable.

Here is my attempt, which prints the correct status, but is followed by a 1. What is this return value and why does it get printed?!

print eval { ($status == 2) ? print "HIGH " : (($status == 1) ? print "MODERATE " : print "LOW " ) };

With $status = 0, this prints: "LOW 1"

Replies are listed 'Best First'.
Re: Multiple if-else statements using C-style ternary operator
by Marshall (Canon) on Jul 11, 2011 at 22:44 UTC
    An even more concise coding doesn't use any if logic at all.
    my @status_text = qw(LOW MODERATE HIGH); my $status = 2; print $status_text[$status];
Re: Multiple if-else statements using C-style ternary operator
by james2vegas (Chaplain) on Jul 11, 2011 at 22:41 UTC
    This should be enough:
    print $status == 2 ? "HIGH " : $status == 1 ? "MODERATE " : "LOW ";
Re: Multiple if-else statements using C-style ternary operator
by spazm (Monk) on Jul 11, 2011 at 22:46 UTC
    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.
      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?

Re: Multiple if-else statements using C-style ternary operator
by BrowserUk (Patriarch) on Jul 11, 2011 at 22:43 UTC

    Simpler way:

    print +( qw[LOW MODERATE HIGH] )[ $_ ] for 0,1,2;; LOW MODERATE HIGH

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Multiple if-else statements using C-style ternary operator
by gansvv (Initiate) on Jul 11, 2011 at 22:36 UTC
    Agh, noticed the error soon after hitting create.

    Removed the "print" before the eval.