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

I am not a big fan of using the ref() function. So when I test to see if a reference is defined, I often use:
if(defined @$arrayref && @$arrayref) { # do something with @$arrayref like: for my $i (@$arrayref) { print $i; } }
I have always been under the impression that this if construct prevents perl from dying if $arrayref is undefined or not an actual array reference. I came across some code today, however, that makes me question that belief.
#!/usr/bin/perl use strict; my $arrayref = []; if(defined @$arrayref) { print "arrayref defined\n"; } else { my $ref = ref $arrayref; print "arrayref not defined ref=$ref\n"; }
This returns: "arrayref not defined ref=ARRAY" But if I change this line:
my $arrayref = [];
to
my $arrayref;
I get the same result. So the question is, does: if(defined @$arrayref) actually test for definition of the array reference in such a way that you could then perform operations on @$arrayref from within the block without crashing Perl?

Replies are listed 'Best First'.
Re: Testing for definition of references
by fglock (Vicar) on Jun 26, 2003 at 18:03 UTC
    if( defined $arrayref && defined @$arrayref )

    should do it, but

    if( defined $arrayref && ref( $arrayref ) eq 'ARRAY' )

    looks better to me.

    This will test if the array has elements:

    if( @$arrayref )
      Thanks, but I actually am trying to avoid using ref() if possible. Also, you are testing:
      if(defined $arrayref)
      This is insufficient since $arrayref may be set to a scalar value and thus would return true. I don't want to test to see if $arrayref is simply defined, but if the array it references is defined. I use:
      if(defined @$arrayref)
      as a means to distinguish the definition of an array reference from all other types of data. My question relates to whether this is valid test or not.
        Why are you avoiding ref()?

        No, it's not. An empty array will return false!

Re: Testing for definition of references
by jsprat (Curate) on Jun 26, 2003 at 18:10 UTC
    Straight from the horse's mouth (perldoc -f defined):

    Use of "defined" on aggregates (hashes and arrays) is deprecated. It used to report whether memory for that aggregate has ever been allocated. This behavior may disappear in future versions of Perl. You should instead use a simple test for size

    HTH...

      Yes, but if you follow what the perldoc says to do for regular arrays and hashes, but use it on a reference like:
      if(@$arrayref)
      and it is not defined, Perl will crash. This is what I'm trying to avoid.
        I'm missing something here. You want to know if it is a reference, but you want to avoid using ref. Is there a reason why (besides not being a fan)? That's exactly what ref was designed to do.