Testing for bless-edness in Perl

Using ref($o) to test whether $o is an object is obviously not enough, as it might be a simple unblessed reference. The following solution is almost perfect:

UNIVERSAL::can($o,'isa')
This tests if $o is a descendant of UNIVERSAL, where the isa method is defined.

However, the above is also true of classes! That is, in the following case, the condition is true:

package mypackage;

package clientcode;
if( UNIVERSAL::can('mypackage','isa') ){ ... }
As an aside, let me note that isa can also be called in a class context, which means that the following is also true:

package mypackage;

package clientcode;
$o = 'mypackage';
if( $o->isa('mypackage') ){ ... }
All in all, it seems the only reliable way of testing whether something is an object is to test whether it can 'isa' and to test whether it is a reference as well.

Popular Posts