Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello the following code produces warnings when run with -w could I please get an explanation on how to properly and eloquently deal with and undefined array?

use strict; use warnings; my @array = undef; if (@array eq undef) { print }; if (@array ne undef) { print }; foreach (@array) { print; } map { print } @array;

Replies are listed 'Best First'.
Re: Question about foreach/iterating/verifying an undefined array
by GrandFather (Saint) on May 21, 2011 at 23:26 UTC

    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.

    True laziness is hard work
Re: Question about foreach/iterating/verifying an undefined array
by LanX (Saint) on May 21, 2011 at 23:17 UTC
    I think you want to empty your array, so use @array=(); (update: or undef @a;)

    my @array = undef; assigns a 1-element list with value undef

    HTH!

    Cheers Rolf

    PS: writing my @a is already sufficient for having an empty array!