Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re^5: Blessing with unknown classnames

by haukex (Archbishop)
on Apr 02, 2021 at 09:32 UTC ( [id://11130717]=note: print w/replies, xml ) Need Help??


in reply to Re^4: Blessing with unknown classnames
in thread Blessing with unknown classnames

I mean this: if (defined $err) can become if (defined($err) && ($err eq 'YouveGotError')), so that it errors only on'YouveGotError' blessed refs and nothing else, because the sub may normally return other blessed things.

I'm not sure if this is a question, but just in case, note that I fully agree with kcott that Scalar::Util's blessed (a core module) is the "correct" answer to the question of how to tell if a reference is blessed or not. But if the sub also can return other blessed refs, and you want to differentiate them, then one possible solution is what you said in your root node: creating an "error" class is one way. But since Perl's OO system is so nice and simple, inheritance can be incredibly simple, as I show in the following example. Of course, there are existing solutions on CPAN, e.g. Throwable and Exception::Class.

use warnings; use strict; use Scalar::Util qw/blessed/; @Error::ISA = qw//; # "base class" for errors @BadInput::ISA = qw/Error/; sub doit { my $in = shift; if ( $in =~ /foo/ ) { return bless [123,456], 'RealReturnValue'; } else { return bless ['abc','def'], 'BadInput'; } } for my $val ("foobar", "quzbaz") { my $ret = doit($val); if ( my $err = blessed $ret and $ret->isa('Error') ) { print "$val -> Error: $err\n"; } else { print "$val -> OK\n"; } } __END__ foobar -> OK quzbaz -> Error: BadInput

Replies are listed 'Best First'.
Re^6: Blessing with unknown classnames
by bliako (Monsignor) on Apr 02, 2021 at 11:12 UTC
    @Error::ISA = qw//; # "base class" for errors @BadInput::ISA = qw/Error/;

    Neat! I guess this is some kind of "class autovivification" you are doing?

    e.g. Throwable

    I prefer to keep it simple and mooless

      I guess this is some kind of "class autovivification" you are doing?

      Like I said, Perl's object system is very simple: ->isa('Error') (inherited from UNIVERSAL) is just looking up the inheritance tree, and the inheritance tree is defined by each package's @ISA, which is just an array of strings, so that's all I needed to define to make the "classes" "exist". perlmod is a good read on this topic.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11130717]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2024-03-28 10:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found