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.