Establishing a Default Value
Problem
You would like to give a default value to a scalar variable, but only if it doesn’t already have one. It often happens that you want a hard-coded default value for a variable that can be overridden from the command-line or through an environment variable.
Solution
Use the ||
or ||= operator,
which work on both strings and numbers:
# use $b if $b is true, else $c $a = $b || $c; # set $x to $y unless $x is already true $x ||= $y
If 0 or "0" are valid values
for your variables, use
defined
instead:
# use $b if $b is defined, else $c $a = defined($b) ? $b : $c;
Discussion
The big difference between the two techniques
(defined and ||) is what they
test:
definedness versus truth. Three defined values are still false in the
world of Perl: 0, "0", and "".
If your variable already held one of those, and you wanted to keep
that value, a || wouldn’t work. You’d
have to use the clumsier tests with defined
instead. It’s often convenient to arrange for your program to
care only about true or false values, not defined or undefined ones.
Rather than being restricted in its return values to a mere 1 or
as in most other languages, Perl’s ||
operator has a much more interesting property: It returns its first
operand (the left-hand side) if that operand is true; otherwise it
returns its second operand. The
&&
operator also returns the last evaluated expression, but is less often used for this property. These operators don’t care whether their operands are strings, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access