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

Hi Monks!

Trying here to verify if an array ref is empty, but this error:
Can't use an undefined value as an ARRAY reference
Trying like this:

Sample 1:
It works if the array ref has elements
my $data = data(); my $count = scalar(@$data); # $#$data; print $count;
Sample 2:
It does not work if the array ref returns nothings my $data = data(); my $count = scalar(@$data); # $#$data; print $count;
Sample 3:
Works but gives me count of 1, since "undef" is been counted I would like to see 0.
my @count = $data; my $count = @count; print $count;

Thanks for helping!

Replies are listed 'Best First'.
Re: Count elements in array ref
by Your Mother (Archbishop) on Mar 29, 2016 at 18:10 UTC

    scalar is unnecessary due to context. This is an idiom I like.

    my $data = data(); my $count = @{ $data || [] };
      Just got it, but you were faster, thank you!
Re: Count elements in array ref
by Corion (Patriarch) on Mar 29, 2016 at 18:01 UTC

    Why don't you just check whether data() returned something?

    Alternatively, have data() return an empty arrayref when there is nothing to return.

Re: Count elements in array ref
by JohnCub (Beadle) on Mar 29, 2016 at 18:06 UTC
    You could try:
    my @Data = (); @Data + 0; my $Count = scalar(@Data); print $Count;
    Outputs: 0 whereas:
    my @Data = ("asdf","345"); @Data + 0; my $Count = scalar(@Data); print $Count;
    Outputs: 2

      I don't understand the purpose of the  @Data + 0; statement in your code examples. Could you please explain? (Note that they produce "Useless use of addition (+) in void context at ..." warnings if warnings are enabled.)


      Give a man a fish:  <%-{-{-{-<

        According to the camel book, that's a way to force an array to a scalar context. Their example is @days + 0;  # implicitly force @days into a scalar context I'm afraid I don't understand it any more than that.
Re: Count elements in array ref
by hippo (Archbishop) on Mar 30, 2016 at 09:16 UTC

    Maybe I'm missing the point here, but is there some reason that you don't use the $#$ construct? You even have it in your comments.

    #!/usr/bin/env perl use strict; use warnings; use Test::More tests => 3; my $data = ['alpha', 'beta']; my $count = $#$data + 1; is ($count, 2, 'With elements'); $data = []; $count = $#$data + 1; is ($count, 0, 'Without elements'); $data = undef; $count = $#$data + 1; is ($count, 0, 'As undef');

    By my reading of your post this seems to satisfy all your criteria and is both clear and concise. HTH.