Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: elegant way to check if something is object blessed as package?

Tags:

perl

bless

I want to check if a $thing is an object blessed as a package (e.g. __PACKAGE__). One idea is:

use Scalar::Util qw(blessed);

defined blessed $thing && blessed $thing eq __PACKAGE__

Is there a better and/or more elegant way that avoids checking if the return value of blessed is defined?

Another approach is (blessed $thing or '') eq __PACKAGE__, but I'm not sure if a package can legally be empty or not.

Also, based on Perl Monks, UNIVERSAL::isa($thing, __PACKAGE__) is another way, but that approach is permissive of more things.

like image 975
Moh Avatar asked Feb 24 '14 06:02

Moh


2 Answers

You can use the predefined ref function:

ref($thing) eq __PACKAGE__

That said, I think the more-permissive isa is really better practice. You shouldn't generally need to check if an object's type is exactly something.

[…] I'm not sure if a package can legally be empty or not.

It cannot. (And incidentally, if you try to bless a reference to '', it will actually get blessed into main. Perl will warn you about this, provided you have -w or use warnings.)

like image 54
ruakh Avatar answered Nov 05 '22 15:11

ruakh


Use the Safe::Isa module from CPAN:

$possible_object->$_isa('DateTime')
like image 44
Alexander Hartmaier Avatar answered Nov 05 '22 16:11

Alexander Hartmaier