-1

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?

toolic
  • 57,801
  • 17
  • 75
  • 117
Yasiru G
  • 6,886
  • 6
  • 23
  • 43
  • You appear to want to send a HTML document to the CGI client on error, but I don't see any attempt at this. – ikegami Oct 22 '15 at 04:56
  • @ikegami: Yes, that's the plan. For now I just trying to catch the error from read_file($file) command. – Yasiru G Oct 22 '15 at 05:11
  • So why did you rule out 1)? – ikegami Oct 22 '15 at 05:13
  • @ikegami: If 1) worked then I can use try/catch and give HTML error report when dies. Its just debugging one – Yasiru G Oct 22 '15 at 05:15
  • I asked why do you say it doesn't work. Not sure why you replied what you would do if it worked. – ikegami Oct 22 '15 at 05:20
  • It didn't work as expected. Code: my @lines = read_file("/etc/asterisk/voicemailq.conf") or die("file read failed\n"); output: Status: 500 Content-type: text/html

    Software error:

    read_file 'test.pl' - sysopen: No such file or directory at //test.pl line 15
    

    For help, please send mail to this site's webmaster, giving this error message and the time and date of the error.

    – Yasiru G Oct 22 '15 at 05:25
  • So `read_file` throws an exception on error rather than returning false like 1) expects. So why did you rule out 2) which catches exceptions? – ikegami Oct 22 '15 at 05:27
  • Well that's a good question. :) gonna try it now. But I was expecting it to pint "file read failed\n" in somewhere. and it confused me. – Yasiru G Oct 22 '15 at 05:29
  • Thanks a LOT @ikegami. It worked. you save my day! – Yasiru G Oct 22 '15 at 05:31

1 Answers1

0

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.

mbethke
  • 935
  • 8
  • 19