in reply to Asking An Object For It's Class
TMTOWTDI:
use Scalar::Util qw(blessed); if (my $class=blessed $foo) { print "Its an object of class $class\n"; } else { print "Its not an object\n"; }
This has the advantage that you can discriminate a blessed reference from an un-blessed one safely, regardless as to what package name it has been blessed into, and avoids the painful filtering of unblessed references which requires overload::StrVal and regexes if you want to be thorough. There is also a function called reftype() which does the converse, telling you what the underlying type is and not what type its blessed into.
#!perl -l use Scalar::Util qw(blessed reftype refaddr); use overload; *isa=*UNIVERSAL::isa; *StrVal=*overload::StrVal; my $array=[]; my $Array=bless [],'ARRAY'; my $hash={}; my $Evil_Hash=bless {},'ARRAY'; foreach my $name (qw($array $Array $hash $Evil_Hash)) { my $ref=eval $name; print "Testing '$name'"; print "ref :",ref $ref; print "U::isa :",isa($ref,'ARRAY'); print "->isa :",eval { $ref->isa('ARRAY') } || do{ chomp($e=$@) +; $e}; print "StrVal :",StrVal($ref); print "blessed :",blessed($ref); print "reftype :",reftype($ref); print "refaddr :",refaddr($ref); print "----" } __END__ Testing '$array' ref :ARRAY U::isa :1 ->isa :Can't call method "isa" on unblessed reference at D:\Temp\bl +essed.pl line 18. StrVal :ARRAY(0x1ab25f0) blessed : reftype :ARRAY refaddr :27993584 ---- Testing '$Array' ref :ARRAY U::isa :1 ->isa :1 StrVal :ARRAY=ARRAY(0x1ab25d8) blessed :ARRAY reftype :ARRAY refaddr :27993560 ---- Testing '$hash' ref :HASH U::isa : ->isa :Can't call method "isa" on unblessed reference at D:\Temp\bl +essed.pl line 18. StrVal :HASH(0x1abf0b8) blessed : reftype :HASH refaddr :28045496 ----
Testing '$Evil_Hash' ref :ARRAY U::isa :1 ->isa :1 StrVal :ARRAY=HASH(0x1abf1a8) blessed :ARRAY reftype :HASH refaddr :28045736 ----
|
|---|