in reply to If / elses

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

Replies are listed 'Best First'.
Re: (Ab)?using logical operators.
by merlyn (Sage) on Mar 12, 2001 at 23:32 UTC
    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!