Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: (tye)Re: ref, no, maybe?

by clintp (Curate)
on Jan 11, 2001 at 05:35 UTC ( [id://51052] : note . print w/replies, xml ) Need Help??


in reply to (tye)Re: ref, no, maybe?
in thread ref, no, maybe?

>By the way, how do you tell if a reference is blessed without using the fragile hack

I've always used variations of:

if ($type = ref $t) { eval { $t->isa("UNIVERSAL"); }; if ( $@=~/unblessed/ ) { print "It's a $type, not blessed.\n" } else { print "It's blessed into class $type"; } } else { print "Not a reference at all\n"; }
with great success. It may not catch everything, and normally I'm not hunting around to figure out what's in a variable... If you don't know, you're in bigger trouble than this. :)

Replies are listed 'Best First'.
can in Re: ref, no, maybe?
by jeroenes (Priest) on Jan 11, 2001 at 14:04 UTC
    This thread strongly reminds me of Readonly error on $_. In his response, merlyn displays some trick using the can method. /me thinks it can be applied here also. Saves the use of UNIVERSAL, but uses eval.
    if eval( $r->can('can')) { #we have an object } elsif ref( $r) { #we have an unblessed reference } else { #no reference at all }
    Merlyn's solution looks somewhat cleaner to me. What do you think?

    Jeroen
    I was dreaming of guitarnotes that would irritate an executive kind of guy (FZ)

      I'd rewrite your code like this:

      if( ! ref($r) ) { #no reference at all } elsif( ! eval { $r->can('can') } ) { #unblessed ref } else { #blessed ref }
      because I think the eval{} seems likely to be more expensive than the ref(). But even more important, if $r is, for example, the simple string "My::Package", then $r->can('can') will succeed (which is also a bug in merlyn's version), even if there is no package called My::Package. In fact, try "This is a test"->can('can') for fun. (:

      As for the difference between eval { $r->can('can') } and eval { $r->isa('UNIVERSAL') }, the only advantage I see to the first is fewer keystrokes. I find the latter clearer, personally. But that gave me the idea for $r->can('isa'), which I find clear (as well as short). I guess isa() screams "object" to my brain faster than can() does, not sure why.

              - tye (but my friends call me "Tye")
(tye)Re2: ref, no, maybe?
by tye (Sage) on Jan 11, 2001 at 05:45 UTC

    Ah, thanks. I was wanting to use it to avoid the eval, so I guess I'll just keep the eval. (:

            - tye (but my friends call me "Tye")