tags:

views:

179

answers:

3

I'm passed a reference, and I want to know its type. For this purpose, "ref" works on unblessed references, but on blessed references it returns the package name it was blessed with.

     $a=[];
     print ref $a;

ARRAY

     bless $a, 'mytype';
     print ref $a;

mytype

How can I get the type?

+15  A: 
use Scalar::Util 'reftype';
print reftype bless {}; # HASH
jrockway
pedantically, use Scalar::Util 1.01 'reftype'; since reftype was added less than 10 years ago, some poor souls may be lacking it.
ysth
+7  A: 

You can use Scalar::Util::reftype for this, but in general it isn't something that you need to do. Usually people asking this question indicates they are doing something else in a less than ideal way. So, why do you think you need to know?

ysth
It's true. Once you bless something, you shouldn't access the underlying data directly. (Sometimes it's useful to do anyway, though, if you are Data::Dumper or Data::Visitor or something.)
jrockway
I know what I'm doing; namely, implementing something akin to Data::Dumper but into a specific format.
niXar
You should implement a dump() method on the object that you can call, which will do Data::Dumper-like activities and keep the type-aware code locked inside the module.
Ether
No, he should use Data::Visitor.
jrockway
A: 

As stated in a comment above.. you are incorrect if you think that external code needs to be aware of the implementation details of a blessed object. If you need to do something like Data::Dumper on the object, create a dump() method on the module which contains the implementation logic. You could add some code into the UNIVERSAL class's autoloader so that it just calls Data::Dumper if you attempt to call dump() on an object that doesn't define it.

Ether