Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

How do I test if a 'thing' is a hash (or array or scalar)?

by Anonymous Monk
on Sep 12, 2000 at 20:51 UTC ( [id://32129]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question: (hashes)

How do I test if a 'thing' is a hash (or array or scalar)?

Originally posted as a Categorized Question.

  • Comment on How do I test if a 'thing' is a hash (or array or scalar)?

Replies are listed 'Best First'.
Re: How do I test if a 'thing' is a hash (or array or scalar)?
by tye (Sage) on Sep 12, 2000 at 22:04 UTC

    But ref() won't tell you whether a blessed reference is a reference to a scalar, array, hash, or other. A better approach is:

    UNIVERSAL::isa( $ref, "HASH" )
            - tye (but my friends call me "Tye")

    Q&A Editor comment: See Library entry: perlman:lib:UNIVERSAL

      When I find myself in this situation, I usually just do a regex for HASH or CODE or whatever. Seems to be more efficient than making UNIVERSAL check the (potentially tall) inheritance tree.

      References to my objects tend to be of the form  One=SCALAR(0x80f11bc) or Two=CODE(0x80f7d30).

        To be clear, you are suggesting something like:

        $ref =~ /HASH/
        or
        $ref =~ /(^|=)HASH\b/
        which checks the "stringification" of the reference. But this fails for objects that have stringification overloaded. It is better than ref(), but I still don't want to make code that breaks for such cases. I have seen cases of this, but unfortunately I don't remember where. :(

        If UNIVERSAL::isa() is a pig, then an efficient replacement needs to be provided (Hmmm... that would be an easy XS to write...).

        I didn't think that UNIVERSAL::isa() would search the inheritance tree since whether a blessed reference is a hash or not has nothing to do with inheritance. I hadn't looked into how isa() is implemented. You'll have to read universal.c if you are that interested. I started to and realized I don't have that much time right now.

                - tye (but my friends call me "Tye")
Re: How do I test if a
by merlyn (Sage) on Sep 12, 2000 at 21:06 UTC
    If you have it in $foo, it's a scalar. It can't be an array or a hash, because Perl is strongly typed.

    If you meant "how do I test whether a reference to {something} is a reference to a scalar/array/hash?", then look at the ref function.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://32129]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (2)
As of 2024-04-26 04:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found