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

Here's a simple one ...

I have the following:

print "hi" if $foo == 1; print "bye" if $foo != 1;

I prefer printing lines with ther in-line if for readability later on ... Is there a way to eliminate the second if, so that it works like and "else" statement?

Replies are listed 'Best First'.
Re: If / elses
by aardvark (Pilgrim) on Mar 12, 2001 at 20:10 UTC
    You can use the trinary operator.
    COND ? THEN : ELSE

    $foo == 1 ? print "hi" : print "bye";

    You can read more about trinary operators here

    Get Strong Together!!

Re: If / elses
by Jouke (Curate) on Mar 12, 2001 at 20:03 UTC
    You could use
    $_ = $foo == 1? "hi" : "bye"; print;


    Jouke Visser, Perl 'Adept'

        Great answer.

        For some reason, I expect that several people will be tempted to transform this into:

        print ( $foo == 1 ) ? "hi" : "bye";

        and I just wanted to note that doing so will break it, printing either "1" or "" and then returning the value of "hi" to the "void context" unless the print failed. (But if you have warnings enabled, you will get a warning for the above code.)

        Two ways to fix this are:

        print( ( $foo == 1 ) ? "hi" : "bye" ); print +( $foo == 1 ) ? "hi" : "bye";
                - tye (but my friends call me "Tye")
(Ab)?using logical operators.
by TGI (Parson) on Mar 12, 2001 at 23:28 UTC

    Despite all the splendor of the ternary operator, you could also use logical operators:

    $foo && print $a or print $b;

    Note the precedence of the operators. This code does something very different:

    $foo and print $a || print $b;

    In any case, I'd use the ?: approach.


    Update:

    merlyn corrected that in about two seconds! I now have even better reason to stand by my intuition that ?: is a better way to go.

    So, in light of his comment you'd really need to do some ooogly thing like:

     ($foo and print $a or 1) or print $b;

    Just use the ternary.


    TGI says moo

      No, please don't do this. I've ranted about this in the past. You cannot in general replace
      $x ? $y : $z
      with
      $x and $y or $z
      unless you can also guarantee that $y is always true. And even if you can, the next person down won't necessarily get that, and then copy it without asserting the proper precondition, and whammo both $y and $z get evaluated and then the plane crashes, hundreds of people die, and thousands of relatives sue you for being a lunkhead programmer1.

      So, don't. Just don't.

      -- Randal L. Schwartz, Perl hacker


      1 It could happen!