Why shouldn't I use UNIVERSAL::isa?

前端 未结 7 1120
终归单人心
终归单人心 2021-02-07 07:58

According to this

http://perldoc.perl.org/UNIVERSAL.html

I shouldn\'t use UNIVERSAL::isa() and should instead use $obj->isa() or CLASS->isa().

This means

7条回答
  •  無奈伤痛
    2021-02-07 08:20

    Everyone else has told you why you don't want to use UNIVERSAL::isa, because it breaks when things overload isa. If they've gone to all the habit of overloading that very special method, you certainly want to respect it. Sure, you could do this by writing:

    if (eval { $foo->isa("thing") }) {
         # Do thingish things
    }
    

    because eval guarantees to return false if it throws an exception, and the last value otherwise. But that looks awful, and you shouldn't need to write your code in funny ways because the language wants you to. What we really want is to write just:

    if ( $foo->isa("thing") ) {
         # Do thingish things
    }
    

    To do that, we'd have to make sure that $foo is always an object. But $foo could be a string, a number, a reference, an undefined value, or all sorts of weird stuff. What a shame Perl can't make everything a first class object.

    Oh, wait, it can...

    use autobox;   # Everything is now a first class object.
    use CGI;       # Because I know you have it installed.
    
    my $x = 5;
    my $y = CGI->new;
    
    print "\$x is a CGI object\n" if $x->isa('CGI');   # This isn't printed.
    print "\$y is a CGI object\n" if $y->isa('CGI');   # This is!
    

    You can grab autobox from the CPAN. You can also use it with lexical scope, so everything can be a first class object just for the files or blocks where you want to use ->isa() without all the extra headaches. It also does a lot more than what I've covered in this simple example.

提交回复
热议问题