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.

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.
Oops! How'd a scalar reference sneak by? (We really wanted to print $$aref; in this case.)

For one thing, you can use B::svref_2object (thanks diotalevi!):

use B; sub refcheck { my $ref = shift; return ref(B::svref_2object($ref)) =~ /B::(\w+)/; }
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...)

You could simply strip off the excess information:

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; }
Although I'm sure this has some major drawbacks as well.

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.