TIEHANDLE and deep recursion
- From: Tim Watts <tw+usenet@xxxxxxxxxx>
- Date: Wed, 09 May 2012 19:32:21 +0100
Hi,
I was wondering of some kind soul could tell me what I am doing wrong in the
code below (one module, one test file, minimum case)
I can see why calling print $fh in "sub PRINT" is recursing - but I cannot
find out how to stop it!! Even copying the filehandle (a suggestion via
Google) seems to not work. I've played with "tied" and do not seem to be
able to find the magic to obtain the underlying filehandle so that calling
print() does not immediately redirect to sub PRINT() and thus recurse.
#### SafeFile.pm #####
package SafeFile;
use warnings;
sub TIEHANDLE
{
my ($self, $fh, @options) = @_;
my $data = {
fh => $fh,
@options,
};
return bless $data, $self;
}
sub FETCH {
my ($self) = @_;
return $self->{fh};
}
sub PRINT {
my $self = shift;
my $fh = *{$self->{fh}};
print $fh @_;
}
sub CLOSE
{
my ($self) = @_;
close $self->{fh};
}
sub safewrite {
my $path = shift;
open my $fh, '>', ;
tie *$fh, __PACKAGE__, *$fh,
(
path => $path,
);
return $fh;
}
1;
#### END SafeFile.pm #####
#### test #####
#!/usr/bin/perl
use warnings;
use SafeFile;
my $fh = SafeFile->safewrite('/tmp/wibble');
print $fh "Hello\n";
print $fh "World\n";
close $fh;
#### END test #####
% perl test
#### Result #####
Deep recursion on subroutine "SafeFile::PRINT" at SafeFile.pm line 23.
/bin/bash: line 1: 21037 Segmentation fault perl test
shell returned 139
Press ENTER or type command to continue
#### END Result #####
The purpose of this is to redirect a request to open ...., ">somefile"; to
open ..., ">somefile.tmp";
The filehandle $fh should be usuable normally with print etc.
On close($fh), somefile.tmp is closed, and rename()'d (an atomic operation
on Linux) to "somefile" - thus the target file is never in a half written
state at any point.
Any thoughts would be most welcome :)
Cheers,
Tim
--
Tim Watts
.
- Follow-Ups:
- Re: TIEHANDLE and deep recursion
- From: Rainer Weikusat
- Re: TIEHANDLE and deep recursion
- From: Ben Morrow
- Re: TIEHANDLE and deep recursion
- From: Rainer Weikusat
- Re: TIEHANDLE and deep recursion
- Prev by Date: Re: WWW::Mechanize and 3rd party APIs (Google)
- Next by Date: Re: TIEHANDLE and deep recursion
- Previous by thread: How do I find an old Perl module on CPAN?
- Next by thread: Re: TIEHANDLE and deep recursion
- Index(es):
Relevant Pages
|