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

Hello, Perl Gurus,
I am wondering how you can test if a variable is a scalar variable or reference to an array/hash.
Is there any function for such operations?
Thank you. Have a good holiday.
ginger
  • Comment on scalar variable or array reference test

Replies are listed 'Best First'.
Re: scalar variable or array reference test
by Zaxo (Archbishop) on Dec 13, 2003 at 17:10 UTC

    perldoc -f ref

    After Compline,
    Zaxo

Re: scalar variable or array reference test
by pg (Canon) on Dec 13, 2003 at 17:39 UTC

    ref returns the type being referenced, or false if it is not a refernce (you see empty string when we try to use it as a string):

    use strict; use warnings; my $a = 123; my $aref = \$a; my @b = (1,2,3); my $bref = \@b; print "[" . ref($a) . "]\n"; print "[" . ref($aref) . "]\n"; print "[" . ref($b) . "]\n"; print "[" . ref($bref) . "]\n";

    You can also use UNIVERSAL->isa():

    use strict; use warnings; my $a = 123; my $aref = \$a; my @b = (1,2,3); my $bref = \@b; print UNIVERSAL::isa($aref, "SCALAR") + 0, "\n"; print UNIVERSAL::isa($bref, "ARRAY") + 0, "\n";

      Why do people on this site insist upon bolding their replies? Bold is for emphasis. However, you seem to think that everything that isn't code in your post is worthy of emphasis. It's a reply. The OP will probably read it regardless of your bold and just piss off people like me who think it is bad etiquette. This bold thing seems to come in waves. I think the tide's coming back in. I guess it's time to finally add that css entry I've been meaning to do.

      Update: poorly-formed HTML pisses me off as well. Please close your b tag somewhere.

      Update 2: Hey, thanks.

      antirice    
      The first rule of Perl club is - use Perl
      The
      ith rule of Perl club is - follow rule i - 1 for i > 1

Re: scalar variable or array reference test
by punkish (Priest) on Dec 13, 2003 at 23:55 UTC
    The easiest way I can think of is
    if (ref $var eq 'SCALAR') { print "scalar\n"; } elsif (ref $var eq 'ARRAY') { print "array\n"; } elsif (ref $var eq 'HASH') { print "hash\n"; }
    hth.
Re: scalar variable or array reference test
by Anonymous Monk on Dec 13, 2003 at 18:56 UTC
    Thank you very much for the information. It really helps.
    ALl the best.
    ginger