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

I'm not a newbie to Perl or anything but I'm interested to know the specifics on the differences between eq "" and !@array when checking if an array is empty.

my @array; if (@array eq "") { print "TEST1 passed\n"; } if (@array) { print "TEST2 passed\n"; } #### prints TEST2 passed
I know there are many other ways to check this, like checking against $array[0] eq "" (though not very good assuming $array[1] might have data. But why does @array eq "" not catch if it's null'd?

Replies are listed 'Best First'.
Re: differences between eq "" and !
by ikegami (Patriarch) on Dec 14, 2006 at 04:01 UTC

    In @array eq "", @array is a scalar string context. In scalar context, an array returns the number of elements it has (0). Furthermore, since a string is required, the number of elements is converted to a string ("0"). Finally, "0" eq "" is false, so the predicate won't get executed when the array is empty.

    By the way, @array == 0 would work.

Re: differences between eq "" and !
by imp (Priest) on Dec 14, 2006 at 04:08 UTC
    The value obtained by using an array in scalar context is the number of entries in that array - and an empty string is not a number.

    Neither test in the code you provided will print anything, as it is equivalent to this:

    if (0 eq "") { print "TEST1 passed\n"; } if (0) { print "TEST2 passed\n"; }
Re: differences between eq "" and !
by siva kumar (Pilgrim) on Dec 14, 2006 at 06:37 UTC
    @array will return the number of elements in the array. If the array is empty then @array will return 0 not the empty value. Hence @array eq "" will not work for checking empty array. So reform the perl code as if(@array==0) { print "TEST1 passes\n"; }
Re: differences between eq "" and !
by ww (Archbishop) on Dec 14, 2006 at 15:34 UTC
    ... #### prints TEST2 passed
    oh? really?
      Obviously one of those cases where the code was mistranscribed. The context indicates the second test should have a ! in it. Interestingly, if we make that conjectural emendation, Perl 6 says:
      TEST1 passed
      TEST2 passed
      because in Perl 6 arrays in scalar context wait until they see whether it's going to be numeric or string context to decide whether to produce a number or a string. One could view the Perl 6 effort largely as an effort to upgrade to a better FAQ. Or at least a different one... :-)
Re: differences between eq "" and !
by ferreira (Chaplain) on Dec 19, 2006 at 19:36 UTC
    False in Perl is "", 0, undef. So
    $scalar eq "" => (implies) !$scalar
    but
    !$scalar => (implies) one of: ($scalar eq "") ($scalar == 0) (defined $scalar eq "")
    but that can't be transformed naïvely to a conjunction (with or or ||) without warnings for some values.