@my_array = undef;
if (@my_array ) {
print 'TRUE';
} else {
print 'FALSE';
}
This will print TRUE
Why does the array have an element ?
@my_array = undef;
if (@my_array ) {
print 'TRUE';
} else {
print 'FALSE';
}
This will print TRUE
Why does the array have an element ?
In Perl, undef
is a valid value. You can put one (or any number) of undef
s into an array or list.
If you want to remove all elements of an array, do this:
@my_array = ();
See What is Truth? for more on boolean values in Perl. (If you're coming from another language, you may be in for a few other surprises, so it's worth a read.)
Here's a key bit from the article:
defined
andundef
are good for testing and setting scalars. Don't try them with arrays, though. Presently,defined(@array)
returns true if Perl has allocated storage for array something that is weird and not useful to the average programmer. To return an array to its initial state, we say:@array = (); # good
To say
@array = undef
is to make@array
contain a one-element list, with the single element being the scalar valueundef
. This is hardly ever what we want.
One other tip: localize your variables with my
: my @array = ( #whatever );
The array has an element because you assigned one. Consider the following:
@array = undef; # Assigns the value 'undef' to @array
@array = (); # Assigns the empty list to @array
undef @array; # Undefines @array
They look similar, but the first line is different from the other two (which are equivalent). The first line results in array with a single element (the value undef
). The other two result in an empty array. In Perl, undef
is both a value and an operator. The first line uses it as a value, the last line uses it as an operator.
It isn't usually necessary to clear an array. They are empty when declared:
my @array; # There's nothing in here, yet