Search code examples
perlerror-handlingreadfileslurp

How to handle error on File::Slurp read_file properly?


I'm using File::Slurp read_file and write_file functions to updated a file content.

Now I'm focusing on add error handling to it. For that I tried doing following methods for file that not actually exist.

1) read_file($file) or die("file read failed\n"); Not working. Just throwing Status: 500 software error.

2) try{ my @lines = read_file($file); } catch{ print "file cannot read";}; not working.

3) err_mode just like in http://search.cpan.org/~drolsky/File-Slurp-9999.13/lib/File/Slurp.pm#err_mode. Not working.

Is it bad idea to use Perl File::Slurp?


Solution

  • This module's documentation seems outdated and doesn't match the behavior (Edit: it's fixed on CPAN, just the version that comes with Fedora still has the inconsistency) . As documented under err_mode, the default behavior on error is to call croak(), not to return undef as mentioned for read_file(). So yes, you'd either have to use err_mode => 'quiet' to get the return-undef behavior, or use a try/catch block. As you said neither of those worked, what exactly happens? Both of these work fine for me:

    $ perl -MFile::Slurp -MTry::Tiny -e'try { $s=read_file("foo") } catch { die "bummer" };' bummer at -e line 1.

    $ perl -MFile::Slurp -e'$s=read_file("foo", err_mode => "quiet") or die "bummer";' bummer at -e line 1.