[Melbourne-pm] IO::File with Capture for Quota

Paul Fenwick pjf at perltraining.com.au
Wed Oct 15 21:31:36 PDT 2008

(Ooops, originally sent only to Scott, sending to MPM as well)

Scott Penrose wrote:

> Sorry I forgot to mention the problem. If someone uses undef $fh; - which
> is the norm. or close $fh which is also common - then the file handle is
> closed before it gets to DESTORY, and I can't use fstat.

You *may* be able to get around this by stashing your filehandle away where
undef can't get to it.  Change the object from being a reference to a glob
to a reference to something else, and store the glob inside.  Then overload
*{} (the globification operator) to return the glob.  You may also wish to
overload the ${} (scalarification operator) to return the glob as well.
That way it looks and feels like a glob, but you *should* be able to get
access to your open filehandle when someone undef's your object.

However I don't think any of this protects you in the close of a close($fh),
where a built-in is being handed your filehandle, and all the tricks I can
think of to catch this are fallible, except one.

You *can* dup your file after it's been opened.  Provided you know the mode,
you *should* be able to:

	use autodie qw(open);
	open(my $dup_fh, "$mode&", $existing_filehandle);

You now have $dup_fh which *should* remain open even if your original
filehandle closes.  If you can then catch that close (left as an exercise to
the reader), you can stat($dup_fh) to determine the new file size without
needing its name, and without race conditions.  This will also get you
around the problems with undef($fh), for the same reasons.

So, I guess the steps on object creation should be:

	* Create the object.
	* Dup the object using the same mode and stash it.

On object destruction:

	* Grab the dup'ed filehandle from the stash.
	* Get its size.
	* Close the dup'ed filehandle and remove it from the stash.

The stash could live inside the object itself, which would the contain two
filehandles.  The original, which it regularly exposes to the rest of the
world, and the dup, which is kept as insurance.

If you do all this, then it's a really good candidate for a CPAN release.



Paul Fenwick <pjf at perltraining.com.au> | http://perltraining.com.au/
Director of Training                   | Ph:  +61 3 9354 6001
Perl Training Australia                | Fax: +61 3 9354 2681

More information about the Melbourne-pm mailing list