[OT] perl file handle question
Paul LeoNerd Evans
leonerd at leonerd.org.uk
Sat Mar 15 19:51:48 GMT 2008
On Sat, 15 Mar 2008 18:50:09 +0000
Nicholas Clark <nick at ccl4.org> wrote:
> Is there a good clean way to have something that mostly behaves as a file
> handle, but has the file name squirrelled away in it somehow?
A filehandle is a GLOB ref, yes? The actual IO work uses the {IO} portion
of the GLOB ref. Perhaps just use the {SCALAR} part of it for the name?
-----
#!/usr/bin/perl -w
use strict;
sub openfile
{
my ( $filename ) = @_;
open( my $fh, $filename ) or die "Cannot open $filename - $!";
${*$fh}{SCALAR} = $filename;
return $fh;
}
sub filename
{
my ( $fh ) = @_;
return ${*$fh}{SCALAR};
}
sub closefile
{
my ( $fh ) = @_;
close $fh or die "Cannot close ".filename( $fh )." - $!";
}
my $fh = openfile( "/dev/stdin" );
print "A line: " . <$fh>;
print "(Opened from " . filename( $fh ) . ")\n";
closefile($fh);
-----
--
Paul "LeoNerd" Evans
leonerd at leonerd.org.uk
ICQ# 4135350 | Registered Linux# 179460
http://www.leonerd.org.uk/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://london.pm.org/pipermail/london.pm/attachments/20080315/7a6bc6d1/signature.pgp
More information about the london.pm
mailing list