Best way to use "isa" method?

perl

Solution

Here's an update for 2020. Perl v5.32 has the `isa` operator, also known as the class infix operator. It handles the case where the left-hand argument is not an object it returns false instead of blowing up:

use v5.32;
if( $something isa 'Animal' ) { ... }

Problem

What is the "best" way to use "isa()" reliably? In other words, so it works correctly on any value, not just an object. By "best", I mean lack of un-handled corner cases as well as lack of potential performance issues, so this is not a subjective question. This question mentions two approaches that seem reliable (please note that the old style `UNIVERSAL::isa()` should not be used, with reasons well documented in the answers to that Q): ``` eval { $x->isa("Class") } #and check $@ in case $x was not an object, in case $x was not an object use Scalar::Util 'blessed'; blessed $x && $x ->isa($class); ``` The first one uses `eval`, the second uses `B::` (at least for non-XS flavor of Scalar::Util). The first does not seem to work correctly if `$x` is a scalar containing a class name, as illustrated below, so I'm leaning towards #2 (using `blessed`) unless somoene indicates a good reason not to. ``` $ perl5.8 -e '{use IO::Handle;$x="IO::Handle"; eval {$is = $x->isa("IO::Handle")}; print "$is:$@\n";}' 1: ``` Are there any objective reasons to pick one of these two approaches (or a 3rd one i'm not aware of) such as performance, not handling some special case, etc...?

Original source

Related problems