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.

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 (with the -w switch), 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.

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 a later lesson, we'll see how to test for this and take special action when there is no more data available to read.

Next:  The defined Function



Main Menu for this topic