theorbtwo got me to thinking about improperly blessed references (blessed into classes they shouldn't be in) with his post here. How do you determine the true type of a reference? "Use UNIVERSAL::isa!" Right? Wrong!
Take the following (contrived) snippet for example.
Oops! How'd a scalar reference sneak by? (We really wanted to print $$aref; in this case.)my @array = (1, 2, 3); my $aref = \@array; showarray($aref); my $text = 'some text'; my $ref = \$text; my $blessed = bless($ref, 'ARRAY'); # bless the scalar reference into +class ARRAY showarray($blessed); sub showarray { my $aref = shift; local $\ = $/; # set the output record seperator return if (!UNIVERSAL::isa($aref, 'ARRAY')); print ref($aref), ": @$aref"; } __DATA__ ARRAY: 1 2 3 Not an ARRAY reference at reftype.pl line 14.
For one thing, you can use B::svref_2object (thanks diotalevi!):
This will return the underlying C structure type but there are problems with this method (at least for me). Every time I try to use one of the B::C_Structure methods it results in a core dump. (B::PVMG::SvSTASH($object), B::PVLV::TYPE($lref), etc...)use B; sub refcheck { my $ref = shift; return ref(B::svref_2object($ref)) =~ /B::(\w+)/; }
You could simply strip off the excess information:
Although I'm sure this has some major drawbacks as well.sub reftype { my $ref = shift; $ref =~ s/\(.*\)$//; # get rid of the (0x0000000) portion of the ref +erence $ref =~ s/^.*=//; # get rid of the CLASS= portion of the referenc +e return $ref; }
And this brings me back to my original question. How do you determine the true type of a reference?
In reply to Determining the true type of a reference by Mr. Muskrat
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |