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;
Eric Strom
source share