Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does @my_array = undef have an element?

Tags:

arrays

perl

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

This will print TRUE

Why does the array have an element ?

like image 219
joe Avatar asked Nov 27 '22 22:11

joe


1 Answers

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
like image 112
Michael Carman Avatar answered Dec 14 '22 03:12

Michael Carman