Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

can in Re: ref, no, maybe?

by jeroenes (Priest)
on Jan 11, 2001 at 14:04 UTC ( [id://51106] : note . print w/replies, xml ) Need Help??

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

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?

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

Replies are listed 'Best First'.
(tye)Re: can in Re: ref, no, maybe?
by tye (Sage) on Jan 11, 2001 at 19:35 UTC

    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")