Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re^3: Multiple actions triggered by failure to open a file

by kschwab (Vicar)
on Jan 10, 2017 at 16:22 UTC ( [id://1179333]=note: print w/replies, xml ) Need Help??


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

Or just a traditional "if":

if (!open my $log_FH, '>', './testlogifle.txt') { print "Failure to open log file.\n"; die "Failure to open log file.\n"; }

Replies are listed 'Best First'.
Re^4: Multiple actions triggered by failure to open a file
by AnomalousMonk (Archbishop) on Jan 10, 2017 at 17:40 UTC
    if (!open my $log_FH, '>', './testlogifle.txt') { print "Failure to open log file.\n"; die "Failure to open log file.\n"; }

    Note that the lexical  $log_FH in the quoted code is local to the if-block and cannot be used by anything except the open failure-handling code — probably not what GreenLantern intends. Instead, the lexical should be declared outside the block if it is ever to be used there.

    Also, this might be a good occasion to use the otherwise puzzling idiom I see sometimes in bioinformatics code: wrapping the open in an unless-block:

    my $log_FH; unless (open $log_FH, '>', './testlogifle.txt') { print "Failure to open log file.\n"; die "Failure to open log file.\n"; } do_something_with($log_FH); ...


    Give a man a fish:  <%-{-{-{-<

      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"; }
        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)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1179333]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (2)
As of 2024-04-19 18:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found