The following
if( ref $obj eq 'T' )
(obviously) works only for objects of class T but
not for objects blessed to other classes that
inherit from T.
I have come up with two solutions:
1) add the following method to T:
sub isT {};
and then check
if ( $obj->can( 'isT' )
This works except that it is two times slower
that checking the ref (i.e. if (ref $obj eq 'T'. )
2) add a field isT to the object in the constructor
and than check
if ( $obj->{isT} )
This is as fast as checking the ref but it looks
ugly and duplicates the field across all objects.
Is there a more elegant way that would be as fast
as checking the ref?
Koszalek
You can use Class->isa() (see "perldoc UNIVERSAL"):
if( ref($obj)->isa('T') )
{
# class is T or inherits from it
}
HTH
-Chris
*NO*. Use $obj->isa('T') directly, otherwise objects can't override it
if they need to.
Ben
--
The cosmos, at best, is like a rubbish heap scattered at random.
Heraclitus
b...@morrow.me.uk
actaully, you want to do
if( eval { $obj->isa("T") } )
Call isa() directly on the object, and don't care too much about what
is actaully in $obj. If it's not an object, you just get back false,
which is still the right nswer to the question. :)
> actaully, you want to do
>
> if( eval { $obj->isa("T") } )
>
> Call isa() directly on the object, and don't care too much about what
> is actaully in $obj. If it's not an object, you just get back false,
> which is still the right nswer to the question. :)
I fixed my code and then bumped in this very problem
(i.e. Can't call method "isa" without a package or object
reference). I come to perl.misc and there is an answer
before I even asked the question :D.
K.
> actaully, you want to do
>
> if( eval { $obj->isa("T") } )
>
> Call isa() directly on the object, and don't care too much about what
> is actaully in $obj. If it's not an object, you just get back false,
> which is still the right nswer to the question. :)
The only thing is that it is approximately 4x slower on my
simple benchmark compared to just checking the ref, i.e.
if( ref $obj eq 'T' )
But that's the way it has to stay.
K.