Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

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

by ikegami (Pope)
on Jan 12, 2007 at 18:33 UTC ( #594430=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://594430]
help
Chatterbox?
[chacham]: I'm sure this is old, but i just came across it: If you put a million monkeys at a million keyboards, one of them will eventually write a Java program. The rest of them will write Perl programs.
[LanX]: lol
[Corion]: Woo hoo! A new Auralnauts episode!
LanX mean unfair and funny
[LanX]: but most java code looks like from one million monkey using eclipse. ..

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (11)
As of 2018-04-23 16:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?