http://qs321.pair.com?node_id=1179359


in reply to Re^4: Multiple actions triggered by failure to open a file
in thread Multiple actions triggered by failure to open a file

I find that often I do want a lexically scoped file handle. Also, I often find that failure to open a file is a perfectly good reason to have both if and else blocks.

my $logfile = './testlogfile.txt'; if ( open my $log_FH, '>', $logfile ) { do_stuff_and_write_info_to_log_about_it( $log_FH ); } else { print "Failure to open log file.\n"; die "Failure to open log file $logfile for writing.: $!\n"; }

Replies are listed 'Best First'.
Re^6: Multiple actions triggered by failure to open a file
by Anonymous Monk on Jan 11, 2017 at 16:45 UTC
    I'm influenced by Lisp's With-Open-File forms in wanting this code to look more like:
    open my $log, '>>', $logfile and do { # lots of stuff to log 1; } || do { print "Failed to write log file $logfile: $!\n"; die "Failed to write log file $logfile: $!\n"; }
    This has the interesting attribute that if the first do-block does not return true, the error handling block runs for it, possibly allowing multiple error types to be more-or-less gracefully handled together. For many things that's a benefit (but certainly not always)