in reply to Re^2: Filehandles and CSV_XS
in thread Filehandles and CSV_XS

in all honesty, my brain gives up on at least three things - quantum physics, Trump-supporters, and type-globs...

Thanks for making me laugh. :) I'm relieved you didn't mention your brain giving up on use strict, use warnings and lexical variables. You really need to embrace all three. To give a simple example why, notice that this code:

use strict; use warnings; sub fred { my $fname = 'f.tmp'; open( FH, '<', $fname ) or die "error: open '$fname': $!"; print "file '$fname' opened ok\n"; # ... process file here die "oops"; # if something went wrong close(FH); } eval { fred() }; if ($@) { print "died: $@\n" } # oops, handle FH is still open if an exception was thrown. my $line = <FH>; print "oops, FH is still open:$line\n";
is not exception-safe because the ugly global file handle FH is not closed when die is called.

A simple remedy, as noted at Exceptions and Error Handling References, is to replace the ugly global FH with a lexical file handle my $fh, which is auto-closed at end of scope (RAII):

use strict; use warnings; sub fred { my $fname = 'f.tmp'; open( my $fh, '<', $fname ) or die "error: open '$fname': $!"; print "file '$fname' opened ok\n"; # ... process file here die "oops"; # if something went wrong close($fh); } eval { fred() }; if ($@) { print "died: $@\n" } print "ok, \$fh is auto-closed when sub fred exits (normally or via di +e)\n";