Why does @my_array = undef have an element?

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

TRUE open

Why does the array have an element?

+4
source share
3 answers

There is an element in the array because you assigned it. Consider the following:

 @array = undef; # Assigns the value 'undef' to @array @array = (); # Assigns the empty list to @array undef @array; # Undefines @array 

They look the same, but the first line is different from the other two (which are equivalent). The first line leads to an array with one element ( undef value). The other two spawn 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.

Usually there is no need to clear the array. They are declared empty:

 my @array; # There nothing in here, yet 
+25
source

See What is Truth? for more information on booleans in Perl. (If you come from another language, you may have other surprises, so it’s worth reading.)

Here's the key bit from the article:

defined and undef are good for testing and tuning scalars. Do not try them with arrays. Currently, defined(@array) returns true if Perl allocated storage for the array something strange and not useful to the average programmer. To return the array to its original state, we say:

 @array = (); # good 

Say @array = undef - make @array contain a singleton list, and a single element is the scalar value of undef . It almost never happens.

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

+11
source

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

If you want to delete all elements of the array, do the following:

 @my_array = (); 
+8
source

Source: https://habr.com/ru/post/1286346/


All Articles