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

This one I understand fine:
# $z is $x divided by $y, unless $y is zero, in which case $z should b +e zero too if ( $y == 0 ) { $z = 0; } else { $z = $x / $y; }

or more succinctly
$z = $y ? $x / $y : 0;

While I know that this works, I don't understand the construction. Probably because I am no brain surgeon, but hey, you don't start by performing quintuple bypasses either... :)

And I understand this even less.

and more succincly still, though thoroughly unreadable:
$z = $y && $x / $y;

Replies are listed 'Best First'.
Re: Could someone please explain this to me in newbie terms :)
by kennethk (Abbot) on Aug 07, 2009 at 18:34 UTC
    A good quick reference on the operators involved can be found at perlop. Breaking down your two expressions:

    $z = $y ? $x / $y : 0;

    1. Given the ternary Conditional Operator, start with the conditional term.
    2. In Perl, 0 is equivalent to false for logical operators (as are nulls/undefs), so that term is equivalent to $y!=0
    3. If $y is not zero, the ternary returns $x/$y
    4. If $y is zero, the ternary returns 0;
    5. Lastly, $z gets the value returned by ? :

    $z = $y && $x / $y;

    1. Given the binary C style Logical And, start with the first term.
    2. If $y == 0, the first term is false, so return false/0.
    3. If $y != 0, the first term is true so evaluate the second term.
    4. If $x / $y == 0, the second term is false, so return false/0.
    5. If $x / $y != 0, the second term is true, so return true.
    6. When && returns true, it returns the return value of the last expression in the chain, hence $x / $y.

    Hope that's clear...

      To be explicit, $z = $y && $x / $y; construct assigns the value of $y to $z, not necessarily a zero unlike $z = $y ? $x / $y : 0;.
        ... when $y evaluates to a false truth value.
Re: Could someone please explain this to me in newbie terms :)
by moritz (Cardinal) on Aug 07, 2009 at 18:24 UTC
    First you have to understand that when you ask if ($y) { ... }

    and $y is a number, than this is short for if ($y != 0) { ... }.

    The ? : construct is like a short if which returns a value: if the condition is true, the value of the expression between ? and : is evaluated, if not, the expression after the : is evaluated (and returned).

Re: Could someone please explain this to me in newbie terms :)
by raisputin (Scribe) on Aug 07, 2009 at 20:09 UTC
    Thanks guys, that makes sense now :)