[OT] perl file handle question

Dirk Koopman djk at tobit.co.uk
Sat Mar 15 22:10:02 GMT 2008


Paul LeoNerd Evans wrote:
> 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;
> }

You can do things like:-

use IO::File;

$fn = "a_file";
$fh = new IO::File $fn;
$$fh->{fn} = $fn;

You can stash any old stuff in there. You are actually using the {HASH} 
part of the glob. So you are not limited simply to one scalar value.

A lot of the HTTP stuff uses this mechanism to stash their stuff away. 
It is also very convenient for subclassing any of IO::* routines.


More information about the london.pm mailing list