Skip to Main Content
Learning Perl, 5th Edition
book

Learning Perl, 5th Edition

by Randal L. Schwartz, Tom Phoenix, brian d foy
June 2008
Beginner content levelBeginner
352 pages
11h 16m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 5th Edition

The undef Value

What happens if you use a scalar variable before you give it a value? Nothing serious, and definitely nothing fatal. Variables have the special undef value before they are first assigned, which is just Perl’s way of saying, “Nothing here to look at—move along, move along.” If you try to use this “nothing” as a “numeric something,” it acts like zero. If you try to use it as a “string something,” it acts like the empty string. But undef is neither a number nor a string; it’s an entirely separate kind of scalar value.

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 you’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.

Similarly, you could have a string accumulator that starts out empty:

$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 ...

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.
Start your free trial

You might also like

Learning Perl, 6th Edition

Learning Perl, 6th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Beginning Perl

Beginning Perl

Curtis Ovid Poe
Learning Perl 6

Learning Perl 6

brian d foy
Mastering Perl

Mastering Perl

brian d foy

Publisher Resources

ISBN: 9780596520106Supplemental ContentErrata Page