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

I have a function that returns an array ref. Whenever this array is empty for some reason the length is still reported as 1...anyone know what I am doing wrong here? I am going crazy trying to figure this out.....

Here is some psuedo code of what I am doing:

sub foo { my @array; return \@array; } my $a_ref = foo(); print scalar(@$a_ref); #this always seems to be 1...
Anyone know what I am doing wrong here? I feel slightly retarded after looking at this for an hour....

Thanks in advance :-)

Replies are listed 'Best First'.
Re: references to empty arrays
by friedo (Prior) on Feb 14, 2006 at 19:38 UTC
    The code you posted does not do what you say it does. It prints 0, which is what's expected. Try showing some actual code that demonstrates what you're actually trying to do.
      Yep...I found the problem...of course I was looking in the wrong spot...I thought the array was empty...but then I saw that my log was printing to STDOUT and not STDERR so I was missing the note that said I got 1 result hehe....

      At least I was right in saying that I was slightly retarded with regards to this problem....

      Thanks for the help :-)

Re: references to empty arrays
by brian_d_foy (Abbot) on Feb 14, 2006 at 20:45 UTC

    When you wonder what your array looks like, you can always just look. When things don't make sense, look at the data directly. If the data is what you expect but you still get the wrong answers, the problem must be something else.

    use Data::Dumper; my $array_ref = []; print STDERR Dumper( $array_ref );
    --
    brian d foy <brian@stonehenge.com>
    Subscribe to The Perl Review

      It is also wise to learn to use the perl debugger.

      Pseudodebug:

      perl -d program DB<0> c M::N::suspicious_subroutine DB<0> n DB<0> n DB<0> n DB<0> use Data::Dumper DB<0> p Dumper($aref)
Re: references to empty arrays
by davidrw (Prior) on Feb 14, 2006 at 19:41 UTC
    That sample code looks right and also prints 0 for me when i run it ... can you show your exact code? (i suspect you're either doing my @a_ref = foo(); print scalar(@a_ref); or that foo() sets @array to be (undef) ... )