
FileHandle woes: can't use indirect object method invocation?
Hi,
Not long ago I asked whether anyone had made a way to find out the
name of a file (ie the parameter passed to open) from a FileHandle
object.
(The reasons for wanting this are
1) methods that get passed open FileHandles need to be able to issue
warnings about the associated file.
2) I hate seeing
$File->close() or die "Couldn't close $FileName:$!\n";
where $FileName has to be the name that was used to open $File:
what if it's not handly to have around>
)
The general response was "write something to do this yourself".
OK - so I tried. It's appended.
The problem now seems to be that I can't use indirect object method
invocation for methods who's names clash with perl functions. This is
unexpectedly obstructive for perl....
I wanted to create my own 'NamedFile' object, and delegate most of the
method calls to FileHandle. Unfortunately, this causes perl to barf:
$File = new NamedFile;
$File->open(">foo") or die "Couldn't write foo:$!\n";
print $File "Yay\n"; # booo!
On the line marked "booo!" I get from perl:
Not a GLOB reference at ./trial line xxx.
Well - of course it's not: I just want NamedFile::print to get invoked!
OTOH,
$File->print("Yay\n");
works just fine, but this is hardly a 'drop in' replacement for
FileHandle operation!
Thanks for any insights... (including observations about why I
shouldn't be worring about this)!
Martin.
# Since perl won't let us subclass FileHandle, lets use AUTOLOAD to delegate...
package NamedFile;
require 5.003;
use FileHandle;
sub new
{
my $type = shift;
my $self = {};
$self->{'FileName'} = "";
bless $self, $type;
Quote:
}
sub open
{
my $self = shift;
$self->{'NamedFile'} = $_[0];
$self->{'FileHandle'} = new FileHandle;
Quote:
}
sub name
{
return $self->{'NamedFile'};
Quote:
}
sub AUTOLOAD
{
# delegate all other calls to the FileHandle package...
my $self = shift;
my $call = $AUTOLOAD;
$call =~ s/.*:://;
Quote:
}
1;