Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

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 ( #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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://974387]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (3)
As of 2017-12-17 14:38 GMT
Find Nodes?
    Voting Booth?
    What programming language do you hate the most?

    Results (464 votes). Check out past polls.