How to use autodie with non-strict?

The autodie documentation states that it can be used for functions other than those built-in modules that it can handle by default, but there are no clear examples of how to do this in it.

In particular, I would like to use it for the Imager module. Many of the functions and methods of this may fail, and I would prefer that this does not mean that my code will be littered with phrases or die Imager|$image->errstr; .

Of course, if there is another way than using autodie to achieve this, it will be interesting to me too.

+7
source share
3 answers

autodie only works with functions, not methods. This is because it is lexically limited, and the search method cannot be lexically covered. autodie :: hints explains how to tell autodie about user-defined functions, but it will do nothing for methods.

I don’t know how to get autodie-like behavior for methods, unless the module has a built-in (like DBI RaiseError ).

You may have a routine to check, but it will not save all this code, since you still have to pass it the correct object or class to call errstr on.

+4
source
+2
source

Here is an alternative method that works with methods:

 package SafeCall; use Carp (); sub AUTOLOAD { my ($method) = our $AUTOLOAD =~ /([^:']+)$/; #' unshift @_, my $obj = ${shift @_}; my $code = $obj->can($method) or Carp::croak "no method '$method' on $obj"; &$code or Carp::croak $obj->can('errstr') ? $obj->errstr : "calling $method on $obj failed" } 

And use it:

 package Image; sub new {bless {here => 'ok', also => 'can be looked up'}}; sub fails {$_[0]{not_here}} sub succeeds {$_[0]{here}} sub lookup {$_[0]{$_[1]}} sub errstr {'an error occurred'} package main; use 5.010; # for say() my $safe = sub {bless \$_[0] => 'SafeCall'}; # storing the constructor in the scalar $safe allows $safe to be used # as a method: $obj->$safe->method my $img = Image->new; say $img->$safe->succeeds; # prints 'ok' say $safe->($img)->succeeds; # or call this way (also prints 'ok') say $img->$safe->lookup('also'); # prints 'can be looked up' say $img->$safe->fails; # dies with 'an error occurred at file.pl line ##' 
+1
source

All Articles