You can use Perl's eval
statement to catch exceptions, including those from trying to call methods on an undefined argument:
eval {
say $shop->ShopperDueDate->day_name();
};
Since eval
returns the last statement evaluated, or undef
on failure, you can record the day name in a variable like so:
my $day_name = eval { $shop->ShopperDueDate->day_name(); };
If you actually wish to inspect the exception, you can look in the special variable $@
. This will usually be a simple string for Perl's built-in exceptions, but may be a full exception object if the exception originates from autodie or other code that uses object exceptions.
eval {
say $shop->ShopperDueDate->day_name();
};
if ($@) {
say "The error was: $@";
}
It's also possible to string together a sequence of commands using an eval
block. The following will only check to see if it's a weekend provided that we haven't had any exceptions thrown when looking up $day_name
.
eval {
my $day_name = $shop->ShopperDueDate->day_name();
if ($day_name ~~ [ 'Saturday', 'Sunday' ] ) {
say "I like weekends";
}
};
You can think of eval
as being the same as try
from other languages; indeed, if you're using the Error module from the CPAN then you can even spell it try
. It's also worth noting that the block form of eval (which I've been demonstrating above) doesn't come with performance penalties, and is compiled along with the rest of your code. The string form of eval
(which I have not shown) is a different beast entirely, and should be used sparingly, if at all.
eval
is technically considered to be a statement in Perl, and hence is one of the few places where you'll see a semi-colon at the end of a block. It's easy to forget these if you don't use eval
regularly.
Paul