next up previous contents
Next: Assignments Up: Variables Previous: Arrays   Contents

Default Values

In perl, there's never any need to declare a variable before you use it. If you use an unitialized variable in a numeric context, it will take on the value 0; if you use it in a string context, it will take on the value of the empty string (""). Note that an empty string has a length of zero - it does not contain any characters, not even a blank.

Perl will even create arrays on the fly, setting any values you don't specify to an undefined value. Suppose that we refer to an array element, say $ary[3], and that this is the first occurrence of the symbol ary. Perl will fill in the previous values of the array ($ary[0], $ary[1], $ary[2]), and if you refer to them, they will take on the usual default values. Note that single elements of an array, like $ary[3], are scalars, and so they begin with a dollar sign. The expression @ary[3] actually represents an array with a single element, not a scalar, and may cause problems in some circumstances if what you really wanted was a scalar value.

Since undefined values behave like an empty string in a character context and a zero in a numeric context, perl provides a special value known as undef. This allows you to distinguish a variable you've set to zero (or a string you've set to an empty string) from one which takes that value by default. To tell if a variable has already been defined in a perl program, you can use the function defined. If you wish to wipe away all traces of a variable at some point in a program, you can use the undef function, or simply set the variable equal to the value undef. A value of undef is often useful for setting a return value from a function to indicate that no value was returned, as opposed to the usual default of zero or an empty string.


next up previous contents
Next: Assignments Up: Variables Previous: Arrays   Contents
Phil Spector 2002-10-18