Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test that "something" is a hash in Perl?

Tags:

perl

I am receiving a hash of hashes from another function, and some elements of the hash of hashes can be another hash. How can I test to see if something is a hash?

like image 714
SDGator Avatar asked Sep 24 '10 16:09

SDGator


People also ask

How do you check if a hash is defined in Perl?

The exists() function in Perl is used to check whether an element in an given array or hash exists or not. This function returns 1 if the desired element is present in the given array or hash else returns 0.

How can we access hash element in Perl?

Perl Hash Accessing To access single element of hash, ($) sign is used before the variable name. And then key element is written inside {} braces.

How do I pass a hash reference in Perl?

This information can be found by typing perldoc perlref at the command line. Single element slice better written as %{$_[0]} , %{shift} is referring to a hash variable named shift , you probably meant %{+shift} or %{shift @_} .

What do you get if you evaluate a hash in list context in Perl?

When a hash is in LIST context Perl converts a hash into a list of alternating values. Each key-value pair in the original hash will become two values in the newly created list. For every pair the key will come first and the value will come after.


2 Answers

Depending on what you want you will need to use ref or reftype (which is in Scalar::Util, a core module). If the reference is an object, ref will return the class of the object instead of the underlying reference type, reftype will always return the underlying reference type.

if (ref $var eq ref {}) {    print "$var is a hash\n"; }  use Scalar::Util qw/reftype/;  if (reftype $var eq reftype {}) {     print "$var is a hash\n"; } 
like image 59
Chas. Owens Avatar answered Oct 19 '22 23:10

Chas. Owens


Use ref function:

ref($hash_ref) eq 'HASH' ## $hash_ref is reference to hash ref($array_ref) eq 'ARRAY' ## $array_ref is reference to array  ref( $hash{$key} ) eq 'HASH' ## there is reference to hash in $hash{$key} 
like image 37
Ivan Nevostruev Avatar answered Oct 19 '22 22:10

Ivan Nevostruev