in reply to Question about foreach/iterating/verifying an undefined array
First off, "undefined array" is not a useful concept (in Perl anyway). In Perl an array can be empty or not, but not undefined. However, remember that a Perl array is an array of scalar elements and a scalar may have the value 'undef'.
Using @array in a scalar context (in a conditional statement for example) returns a number which is the number of elements in the array. Note however that that is a number so the numeric comparison operators (==, != <, ...) are appropriate, not the string comparison operators (eq, ne, lt, ...).
Now, to address the warning in your code. Consider:
use strict; use warnings; my @array; print "\@array contains ", scalar @array, " elements\n"; print for @array; @array = undef; print "\@array now contains ", scalar @array, " element\n"; for my $index (0 .. $#array) { print "Element at $index: ", (defined $_ ? "'$_'" : "undefined"), +"\n" } @array = (); print "\@array contains ", scalar @array, " elements\n";
Prints:
@array contains 0 elements @array now contains 1 element Element at 0: undefined @array contains 0 elements
Do you see that the assignment @array = undef has almost exactly the opposite effect to the one I suspect you expected? It populates the array with one element which has the value undef! If you want to empty an array assign the empty list () to it.
|
|---|