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

Hi Monks,
how can I check whether the value of a hash is a scalar or a reference to an array or hash?

I think that should be possible, but I've got no Idea how to solve this.

Thanks in advance

Regards
Floh
  • Comment on Check whether a variable is a hash or not

Replies are listed 'Best First'.
Re: Check whether a variable is a hash or not
by kyle (Abbot) on Feb 15, 2007 at 16:41 UTC

    Just to expand a little on the helpful info you've already gotten from davorg and ikegami, ref and Scalar::Util's reftype will both tell you (1) whether what you have is a reference, and (2) what kind of reference it is. The difference between them is what they do with a reference that's been blessed into a class. In that case, ref will give you the class name, and reftype will tell you the type of the unblessed reference.

    Here's an example:

    use Scalar::Util qw( reftype ); my $blessed = bless {}, 'My::Class'; my $hashref = {}; printf "blessed is ref %s\n", ref $blessed; printf "blessed is reftype %s\n", reftype $blessed; printf "hashref is ref %s\n", ref $hashref; printf "hashref is reftype %s\n", reftype $hashref;

    This prints:

    blessed is ref My::Class blessed is reftype HASH hashref is ref HASH hashref is reftype HASH

    Both of them will return undef if you hand them something that is not a reference. Otherwise what's returned is just a regular string that you can compare with eq or pattern matches.

Re: Check whether a variable is a hash or not
by imp (Priest) on Feb 15, 2007 at 17:15 UTC
    You can almost always use either ref or Scalar::Util's reftype, as mentioned by the other monks. The only time that approach would fail is when the object being tested acts like a hash using the magic of overload. In those rare cases the only solution I know is to try and use it like a hash.
    { package fakehash; use overload "%{}" => sub { return {1 => 2} }; sub new {my $c; bless \$c}; } use strict; use warnings; use Scalar::Util qw( reftype ); my $fake = fakehash->new; printf "fake is ref %s\n", ref $fake; printf "fake is reftype %s\n", reftype $fake; # Try to use $fake as a hashref. # The return value of eval should be 1 if the first # statement is successful, as 1 is the last statement executed # in the block # The assignment to (undef) is to avoid this warning: # "Useless use of a variable in void context" if ( eval {(undef) = %$fake; 1}) { print "fake is pretending to be a hashref\n"; }
Re: Check whether a variable is a hash or not
by davorg (Chancellor) on Feb 15, 2007 at 16:03 UTC
Re: Check whether a variable is a hash or not
by gopalr (Priest) on Feb 16, 2007 at 09:06 UTC

    Hi

    Take a look at ref