in reply to How do I test if an array is empty or not?

my $j = 0; for (my $i = 0; $i <= $#array; ++$i) { $current = $array[$i]; if($current == undef) { push @empty, $j++; } } print "undefined indices: @empty \n";
or to put it in common perl terms
my @empties = (); for my $i(0..$#array) { unless(defined $array[$i]) { push @empties, $i; } } print "undefined indices @empties\n";

{Editor's note: This example doesn't work as the poster thought it would. See Abigail-II's explanation here: Re: Answer: How do I test if an array is empty or not?.}

Edited by davido for clarification.

Replies are listed 'Best First'.
Re: Answer: How do I test if an array is empty or not?
by Abigail-II (Bishop) on Aug 21, 2002 at 11:09 UTC
    What your code is trying to do is extracting the undefined values (or rather, the indices) from the array - which is a different question. However, your first code fragment not only finds the indices with undefined values, but anything that is 0 in numeric context, which includes 0, the empty string and the undefined value.

    Your second code fragment is correct, but it can be written in a more Perlesque way:

    my @empties = grep {!defined $array [$i]} 0 .. $#array;

    As for the question, just use the array in scalar context. It's empty if the array is 0 in scalar context.

    Abigail