Learning Perl

Learning PerlSearch this book
Previous: 2.8 Output with printChapter 2
Scalar Data
Next: 2.10 Exercises
 

2.9 The Undefined Value

What happens if you use a scalar variable before you give it a value? Nothing serious, and definitely nothing fatal. Variables have the undef value before they are first assigned. This value looks like a zero when used as a number, or the zero-length empty string when used as a string. You will get a warning under Perl's -w switch, though, which is a good way to catch programming errors.

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.

One operation we've seen that returns undef under certain circumstances is <STDIN>. Normally, this returns the next line that was read; however, if there are no more lines to read (such as when you type CTRL-D at the terminal, or when a file has no more data), <STDIN> returns undef as a value. In Chapter 6, we'll see how to test for this and take special action when there is no more data available to read.


Previous: 2.8 Output with printLearning PerlNext: 2.10 Exercises
2.8 Output with printBook Index2.10 Exercises