Because undef automatically acts like zero when
used as a number, it's easy to make an numeric accumulator that
starts out empty:
# Add up some odd numbers
$n = 1;
while ($n < 10) {
$sum += $n;
$n += 2; # On to the next odd number
}
print "The total was $sum.\n";
This works properly when $sum was
undef before the loop started. The first time
through the loop, $n is one, so the first line
inside the loop adds one to $sum. That's
like adding one to a variable that already holds zero (because
we're using undef as if it were a number).
So now it has the value 1. After that, since
it's been initialized, adding works in the traditional way.
$string .= "more text\n";
If $string is undef, this will
act as if it already held the empty string, putting "more
text\n" into that variable. But if it already holds a
string, the new text is simply appended.
Perl programmers frequently use a new variable in this way, letting
it act as either zero or the empty string as needed.
Many operators return undef when the arguments are
out of range or don't make sense. If you don't do
anything special, you'll get a zero or a null string without
major consequences. In practice, this is hardly a problem. In fact,
most programmers will rely upon this behavior. But you should know
that when warnings are turned on, Perl will typically warn about
unusual uses of the undefined value, since that may indicate a bug.
For example, simply copying undef from one
variable into another isn't a problem, but trying to
print it would generally cause a warning.
| | |
2.10. The while Control Structure | | 2.12. The defined Function |