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

If I have a scalar that refers to an array: $raData

I test if the assignment failed with !$raData,

why doesn't this test for an empty array: !@$raData?

Thanks!!!

Replies are listed 'Best First'.
Re: array test question
by larsen (Parson) on Oct 26, 2002 at 22:11 UTC
    Maybe I missed the point in your question, but this works for me:
    use strict; use warnings; my @v = (1, 2, 3); my $r = \@v; check(); @v = (); check(); sub check { print ((! $r) ? "Empty " : "Non-empty ", "reference\n"); print ((! @$r) ? "Empty " : "Non-empty ", "array\n"); }
    And this is the output:
    Non-empty reference
    Non-empty array
    Non-empty reference
    Empty array
    
Re: array test question
by gjb (Vicar) on Oct 26, 2002 at 21:51 UTC

    Personally I'd test the assignment by !defined $raData and the emptyness by scalar(@$raData) == 0.

    However, as far as I can see, !@$raData seems to test for emptyness as I'd expect with Perl 5.6.1, so I maybe I missed the point of your question?

    Best, -gjb-

Re: array test question
by thpfft (Chaplain) on Oct 27, 2002 at 16:37 UTC

    Your test is sound, but the answer is probably that it depends what happens when 'assignment fails'. An array in boolean context (is there such a thing in perl?) will evaluate to true if it contains anything at all:

    () is false (undef) is true (0) is true

    so if it's coming from a sub that explicitly returns 0 or undef on failure, you'll end up with a populated array. The best thing to do is use just return, since return undef is true in list context. I dimly recall that there occasions when return () is dodgy in scalar context, too, but I can't remember what they are :(

    hth