One of my favourite features in Perl is using the boolean ||
operator to select between a set of choices.
$x = $a || $b;
# $x = $a, if $a is true.
# $x = $b, otherwise
This means one can write:
$x = $a || $b || $c || 0;
to take the first true value from $a
, $b
, and $c
, or a default of 0
otherwise.
In Perl 5.10, there's also the //
operator, which returns the left hand side if it's defined, and the right hand side otherwise. The following selects the first defined value from $a
, $b
, $c
, or 0
otherwise:
$x = $a // $b // $c // 0;
These can also be used with their short-hand forms, which are very useful for providing defaults:
$x ||= 0; # If $x was false, it now has a value of 0.
$x //= 0; # If $x was undefined, it now has a value of zero.
Cheerio,
Paul