joe
joe

Reputation: 35117

Why does @my_array = undef 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 ?

Upvotes: 4

Views: 2363

Answers (3)

Michael Carman
Michael Carman

Reputation: 30851

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

Upvotes: 25

Telemachus
Telemachus

Reputation: 19725

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 );

Upvotes: 11

j_random_hacker
j_random_hacker

Reputation: 51326

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 = ();

Upvotes: 8

Related Questions