I’m trying to transform a hash definition which is stored in a string to an actual hash. This works out great with the eval() function.
I want to however to have the possibility to trap errors when an faulty hash definition is stored in the string.
Why can’t I catch/trap the error which occurs in line 9?
#!/usr/bin/perl
use warnings;
use strict;
my $good_hash = "( 1 => 'one', 2 => 'two')";
my $bad_hash = "[ 1 => 'one', 2 => 'two')";
eval{my %string = eval($good_hash)} or &error;
eval{my %string = eval($bad_hash)} or &error;
sub error(){
print "error\n";
}
The eval operation can throw either errors or warnings.
The error messages from eval are stored in the $@ variable. If there was no error thrown , $@ will be an empty string.
However, warning messages are not stored in the $@ variable. You can process the warnings by using
$SIG{__WARN__}.I think in your case, eval is throwing warnings. One way of handling it would be by doing something like this:
This is simplistic code example and can be improved based on your requirement.