Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: How do I report an error back to the user of my object?

by kennethk (Abbot)
on Jun 04, 2012 at 22:25 UTC ( [id://974387]=note: print w/replies, xml ) Need Help??


in reply to How do I report an error back to the user of my object?

See $! in perlvar. You can't reliably set $!. If you have warnings on, you'll get Argument "Error loading data!" isn't numeric in scalar assignment because $! isn't a normal variable, and expects a numerical system error code. (Re: warnings, see Use strict warnings and diagnostics or die).

The usual way of indicating a failure in Perl is to die, which functions as an exception that can be caught downstream, e.g.

sub new{ my $class = shift; my $self; $self->{name} = 'new'; bless ($self); if ($self->loaddata()){ return $self; }else{ die "Error loading data!"; } }
which could be invoked as my $obj = eval{coolobject->new} or die "$@";

If you absolutely want to pass an error and return an undef, you could set $@ manually, but this is probably poor form.

If you are rolling your own objects for fun/education, I'd recommend you look at perltoot. If you are rolling objects for deployment, I'd look at (and use) some prior art like Moose, Mouse...


<Node text goes above. Div tags should contain sig only>

#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (2)
As of 2024-04-25 20:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found