http://www.perlmonks.org?node_id=594430


in reply to How do I make the garbage collector throw an exception when it fails to auto-close a filehandle?

When a function has special cleanup needs, use tilly's ReleaseAction.

use ReleaseAction qw( on_release ); sub something { ... open my $fh, ... my $closer = on_release { if (defined($fh) && defined(fileno($fh))) { close($fh) or die(...); } }; ... }

$closer holds a reference to $fh, so $closer will get destroyed before $fh. (Not necessarily true if they survive until global destruction.)

  • Comment on Re: How do I make the garbage collector throw an exception when it fails to auto-close a filehandle?
  • Select or Download Code

Replies are listed 'Best First'.
Re^2: How do I make the garbage collector throw an exception when it fails to auto-close a filehandle?
by Aristotle (Chancellor) on Jan 13, 2007 at 07:37 UTC

    Yah, I’m aware of the concept. I would use it (more readily than a special IO class, possibly, although my opinion on that changes every other day), but for a single close $fh or die "Couldn't close: $!" statement it just doesn’t seem worthwhile. It’s maddening – it’s a simple single statement whose absence is not worth complicating the code for, but it’s still annoying to have to write it, and there’s so little missing to make it unnecessary…

    Makeshifts last the longest.

      Nevermind. die in destrutor. Doesn't work.

      use strict; use warnings; use ReleaseAction qw( on_release ); $| = 1; sub something { my $closer = on_release { print "on_release enter\n"; die("test"); print "on_release exit\n"; }; } print "pre\n"; something(); print "post\n";

      outputs

      pre on_release enter (in cleanup) test at script.pl line 11. post

      Tested on 5.6.1 & 5.8.8