tags:

views:

273

answers:

3
@my_array = undef;
if (@my_array ) {  
    print 'TRUE'; 
} else {
    print 'FALSE';
}

This will print TRUE

Why does the array have an element ?

+8  A: 

In Perl, undef is a valid value. You can put one (or any number) of undefs into an array or list.

If you want to remove all elements of an array, do this:

@my_array = ();
j_random_hacker
Alternately, you can do "undef @my_array"
Michael Carman
or $#my_array = -1;. or splice(@my_array,0,@my_array);.
ysth
@Ysth: I'm curious: why not just splice @my_array?From perldoc -f splice: "If both OFFSET and LENGTH are omitted, removes everything."
Telemachus
+11  A: 

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 and undef 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 value undef. This is hardly ever what we want.

One other tip: localize your variables with my: my @array = ( #whatever );

Telemachus
+19  A: 

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
Michael Carman
Side remark: for scalar variables $p = undef and undef $p are equivalent.