You can use the Perl eval operator to throw exceptions, including from attempts to call methods in the undefined argument:
eval { say $shop->ShopperDueDate->day_name(); };
Since eval returns the last processed statement or undef on error, you can write the name of the day in a variable as follows:
my $day_name = eval { $shop->ShopperDueDate->day_name(); };
If you really want to check the exception, you can see the special variable $@ . This will usually be a simple line for Perl's built-in exceptions, but may be the full exception object if the exception comes from autodie or other code that uses object exceptions.
eval { say $shop->ShopperDueDate->day_name(); }; if ( $@ ) { say "The error was: $@ "; }
It is also possible to group a sequence of commands using the eval block. The following will only check if it was on the weekend if we had no exceptions thrown when searching for $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 the same as try from other languages; indeed, if you use the Error module from CPAN, you can even write its try . It is also worth noting that the block form of eval (which I demonstrated above) is not related to performance penalties and compiled along with the rest of your code. The string form of eval (which I haven't shown yet) is a completely different beast and should be used sparingly, if at all.
eval technically considered an assertion in Perl and, therefore, is one of the few places where you will see a half-point at the end of the block. This is easy to forget if you are not using eval regularly.
Floor
source share