perlbless

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


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.


Solution

  • 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.)