http://qs321.pair.com?node_id=149861


in reply to Re: has it been blessed?
in thread has it been blessed?

The second test you pose is probably the more efficient, but you overlook a few candidates:

my $ref; if ($ref = ref($obj) and $ref !~ /^(SCALAR|ARRAY|HASH|GLOB|Regexp) +$/) { $obj->method(); }

Technically, the Regexp references are objects, but they are part of the core, and wouldn't represent an application-defined class. Of course, you can drop that from the regex above, if you like.

--rjray

Replies are listed 'Best First'.
Re: Re: Re: has it been blessed?
by chipmunk (Parson) on Mar 07, 2002 at 02:10 UTC
    Efficiency is nice, but there's something to be said for correctness as well. You've also forgotten REF, CODE, and LVALUE.

    Comparing the return value from ref to a list of known types is simply the wrong approach. Either you'll forget something, or a new type will be added in a future version and your code will break.

    Go with the UNIVERSAL::isa() approach. Really.

      I agree, but to clarify, the best approach would seem to be:

      if (ref($obj) and UNIVERSAL::isa($obj, 'UNIVERSAL')) { ... }

      Well, "best" in absence of the blessed primitive, of course...

      --rjray

        if (UNIVERSAL::isa($obj, 'UNIVERSAL')) { is more than enough. If it's not a reference, UNIVERSAL::isa() will return undef. Don't bother doing a check twice.

        ------
        We are the carpenters and bricklayers of the Information Age.

        Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.