dup a lexical filehandle

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::Dumper;
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
 
A

Anno Siegel

How do you dup a lexical file handle?

With old fashioned handles, you could do:

open my $new_fh, "<&FH" or die $!;

open my $new_fh, '<&', $fh or die "dup: $!";

Anno
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top