Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine the type of a blessed reference in Perl?

Tags:

In Perl, an object is just a reference to any of the basic Perl data types that has been blessed into a particular class. When you use the ref() function on an unblessed reference, you are told what data type the reference points to. However, when you call ref() on a blessed reference, you are returned the name of the package that reference has been blessed into.

I want to know the actual underlying type of the blessed reference. How can I determine this?

like image 626
Ryan Olson Avatar asked Aug 14 '08 14:08

Ryan Olson


People also ask

How do I know the type of a variable in Perl?

Perl provides the ref() function so that you can check the reference type before dereferencing a reference... By using the ref() function you can protect program code that dereferences variables from producing errors when the wrong type of reference is used...

What does bless in Perl mean?

The bless function in Perl is used to associate a reference (usually a reference to a hash) with a package to create an instance.


2 Answers

Scalar::Util::reftype() is the cleanest solution. The Scalar::Util module was added to the Perl core in version 5.7 but is available for older versions (5.004 or later) from CPAN.

You can also probe with UNIVERSAL::isa():

$x->isa('HASH')             # if $x is known to be an object
UNIVERSAL::isa($x, 'HASH')  # if $x might not be an object or reference

Obviously, you'd also have to check for ARRAY and SCALAR types. The UNIVERSAL module (which serves as the base class for all objects) has been part of the core since Perl 5.003.

Another way -- easy but a little dirty -- is to stringify the reference. Assuming that the class hasn't overloaded stringification you'll get back something resembling Class=HASH(0x1234ABCD), which you can parse to extract the underlying data type:

my $type = ($object =~ /=(.+)\(0x[0-9a-f]+\)$/i);
like image 174
Michael Carman Avatar answered Sep 18 '22 00:09

Michael Carman


You probably shouldn't do this. The underlying type of an object is an implementation detail you shouldn't mess with. Why would you want to know this?

like image 44
Leon Timmermans Avatar answered Sep 18 '22 00:09

Leon Timmermans