Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Re^2: Determine Reference Types (TIMTOWWTDI)

by tye (Sage)
on Jun 28, 2006 at 17:58 UTC ( #558093=note: print w/replies, xml ) Need Help??

in reply to Re: Determine Reference Types
in thread Determine Reference Types

Eh, ref and reftype both have their problems. My preference is to use:

*isa= UNIVERSAL::isa; sub whatever { for my $ref ( @_ ) { if( isa( $ref, "HASH" ) ) { # ...

Because it doesn't fail to be useful just because a reference is blessed (like ref does), it is simple, and it is easy to fool it into doing the right thing when it doesn't get it right by default. reftype() won't work for overloaded objects that can behave as a certain type of reference whether or not they are implemented as that type of reference. isa doesn't (by default) handle that case either, but you at least can make your overloaded object inherit from "HASH" and/or "ARRAY" (etc.) in order to get isa() to "do the right thing".

There really needs to be some "canBe" added to the Perl core that correctly handles all of these cases. I'd write or search for a module to determine allowed reference types that was aware of overload, but such not being in the core would make it fairly useless to me, personally.

On the rare occassion when I really want to do the extra effort in order to get this type of thing right (rather than doing something simple that works in most cases and can be fooled to work in the others), I use eval (as with Data::Diver):

sub whatever { for my $ref ( @_ ) { if( !ref($ref) ) { # Not a reference } elsif( eval { my $x= $ref->{''}; 1 } ) { # It can be used as a hash ref # ...

But that isn't absolutely perfect because it will invoke a FETCH method that might be broken enough to change some state somewhere, making our test intrusive. But I can at least shift some of the blame to the author of the "broken" FETCH method, so it is the best I've implemented.

Note that I didn't go the route of figuring out how to decide if was providing the functionality as it wasn't too long ago when this stuff changed and my eval trick will work even if it changes again. Better would be a core module that safely makes the determination and stays up-to-date.

Note that some hate the use of isa() because it can be fooled into doing the wrong thing. I don't see that as a problem in most situations, and sometimes it can be useful. But you should be aware of that.

- tye        

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (6)
As of 2022-06-27 12:35 GMT
Find Nodes?
    Voting Booth?
    My most frequent journeys are powered by:

    Results (88 votes). Check out past polls.