I love doing this sort of thing in Perl: $foo = $bar || $baz
to assign $baz
to $foo
if $bar
is empty or undefined. You al
I think in general doing something like this:
$foo = $bar || $baz;
is a bad idea, unless $bar
and $baz
are both booleans. If they arent:
$bar = 10;
$baz = 11;
then the question becomes: what determines if something is true or false? Most
people would probably expect zero to be false, and everything else to be true.
But with some languages (for example Ruby), only false
and nil
are false,
which means both 0
and 1
would be true. Because of this cross language
ambiguity, I think it best to be explicit in these cases:
if ($bar !== 0) {
$foo = $bar;
} else {
$foo = $baz;
}
or:
$foo = $bar !== 0 ? $bar : $baz;