X
xhoster
How do you dup a lexical file handle?
With old fashioned handles, you could do:
open my $new_fh, "<&FH" or die $!;
But I don't want to have FH, I need to use $fh.
In case this is an XY problem, what I'm trying to do is subclass a module
whose constructor only takes a filename, but I want my hands on the handle,
so I want to trick the super class into duping a handle when it ties to
open a file.
use strict;
use warnings;
use Data:
umper;
my $x=Bar->new('/dev/random');
my $y=Bar->new('/dev/null');
# now $x and $y contain same handle, not separate ones.
package Legacy;
sub new {
my ($class, $name)=@_;
open SRC, $name or die "$name $!";
my $self={content=>[map ord scalar <SRC>,1..10]};
close SRC;
bless $self, $class;
};
package Bar;
use Carp;
our @ISA=qw(Legacy);
sub new {
my ($class,$name)=@_;
open (Bar::FH, $name) or die "$name $!";
# Maybe lock FH here
my $self=Legacy->new('<&Bar::FH');
# do other stuff with FH here, maybe even store it:
$self->{filehandle}=\*Bar::FH;
bless $self, $class;
};
Thanks,
Xho
With old fashioned handles, you could do:
open my $new_fh, "<&FH" or die $!;
But I don't want to have FH, I need to use $fh.
In case this is an XY problem, what I'm trying to do is subclass a module
whose constructor only takes a filename, but I want my hands on the handle,
so I want to trick the super class into duping a handle when it ties to
open a file.
use strict;
use warnings;
use Data:
my $x=Bar->new('/dev/random');
my $y=Bar->new('/dev/null');
# now $x and $y contain same handle, not separate ones.
package Legacy;
sub new {
my ($class, $name)=@_;
open SRC, $name or die "$name $!";
my $self={content=>[map ord scalar <SRC>,1..10]};
close SRC;
bless $self, $class;
};
package Bar;
use Carp;
our @ISA=qw(Legacy);
sub new {
my ($class,$name)=@_;
open (Bar::FH, $name) or die "$name $!";
# Maybe lock FH here
my $self=Legacy->new('<&Bar::FH');
# do other stuff with FH here, maybe even store it:
$self->{filehandle}=\*Bar::FH;
bless $self, $class;
};
Thanks,
Xho