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.
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.)
Use the Safe::Isa module from CPAN:
$possible_object->$_isa('DateTime')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With