How can I determine the type of a blessed reference in Perl?

后端 未结 3 506
长情又很酷
长情又很酷 2020-12-30 01:31

In Perl, an object is just a reference to any of the basic Perl data types that has been blessed into a particular class. When you use the ref() function on an unblessed re

相关标签:
3条回答
  • 2020-12-30 01:54

    And my first thought on this was: "Objects in Perl are always hash refs, so what the hack?"

    But, Scalar::Util::reftype is the answer. Thanks for putting the question here.

    Here is a code snippet to prove this.. (in case it is of any use to anyone).

    $> perl -e 'use strict; use warnings "all";
                my $x = [1]; bless ($x, "ABC::Def");
                use Data::Dumper; print Dumper $x;
                print ref($x) . "\n";
                use Scalar::Util "reftype"; print reftype($x) . "\n"'`
    

    Output:

    $VAR1 = bless( [
                     1
                   ], 'ABC::Def' );
    ABC::Def
    ARRAY
    
    0 讨论(0)
  • 2020-12-30 02:05

    Scalar::Util::reftype() is the cleanest solution. The Scalar::Util module was added to the Perl core in version 5.7 but is available for older versions (5.004 or later) from CPAN.

    You can also probe with UNIVERSAL::isa():

    $x->isa('HASH')             # if $x is known to be an object
    UNIVERSAL::isa($x, 'HASH')  # if $x might not be an object or reference
    

    Obviously, you'd also have to check for ARRAY and SCALAR types. The UNIVERSAL module (which serves as the base class for all objects) has been part of the core since Perl 5.003.

    Another way -- easy but a little dirty -- is to stringify the reference. Assuming that the class hasn't overloaded stringification you'll get back something resembling Class=HASH(0x1234ABCD), which you can parse to extract the underlying data type:

    my $type = ($object =~ /=(.+)\(0x[0-9a-f]+\)$/i);
    
    0 讨论(0)
  • 2020-12-30 02:05

    You probably shouldn't do this. The underlying type of an object is an implementation detail you shouldn't mess with. Why would you want to know this?

    0 讨论(0)
提交回复
热议问题