ice94 has asked for the wisdom of the Perl Monks concerning the following question:

Hi everyone. First of all, I am still a Perl newbie and I'm trying to figure out the wonders of this language. Now that the pleasantries are over, let me submit to you my question : I am not able to catch errors thrown by the YAML module (YAML_PARSE_ERR_INCONSISTENT_INDENTATION, YAML_PARSE_ERR_NO_SEPARATOR...). I have tried the classic :
my $var = LoadFile($fh) or warn/die "MESSAGE";
but I still cannot catch anything :
YAML Error: Inconsistent indentation level Code: YAML_PARSE_ERR_INCONSISTENT_INDENTATION Line: 21 Document: 1 at /usr/share/perl5/YAML/Loader.pm line 719
Here is my code :
#!/usr/bin/env perl use strict; use Getopt::Long; use YAML qw(LoadFile); use Data::Dumper; my $file; GetOptions ( "file=s" => \$file); if ( $file ) { $SIG{__DIE__} = sub { die("My error: ", @_); }; $SIG{__WARN__} = sub { warn("My warning: ", @_); }; open my $fh, '<', $file or die "Cannot open target file\n"; #THIS ERROR IS CATCHABLE my $config = LoadFile($fh) or warn("YAML parsing error\n"); #CANNOT CATCH ERROR #or warn "YAML parsing error\n"; #CANNOT CATCH ERROR print Dumper(\$config), "\n"; } else { die "Syntax: $0 [-f,--file] [YAML_FILE]"; }
Can you please provide with any help ? Thank you in advance. Regards.

Replies are listed 'Best First'.
Re: YAML - Catch errors
by MidLifeXis (Monsignor) on May 27, 2014 at 14:30 UTC

    See eval, Try::Tiny, or some other exception handler for this.

    --MidLifeXis

      Indeed, a simple eval did the job :
      eval { $config = LoadFile($fh); } or die "CANNOT EVAL\n";
      Thanks for your help.