Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Perl > Perl Misc > dup a lexical filehandle

Reply
Thread Tools

dup a lexical filehandle

 
 
xhoster@gmail.com
Guest
Posts: n/a
 
      02-11-2006
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

--
-------------------- http://NewsReader.Com/ --------------------
Usenet Newsgroup Service $9.95/Month 30GB
 
Reply With Quote
 
 
 
 
Anno Siegel
Guest
Posts: n/a
 
      02-11-2006
<(E-Mail Removed)> wrote in comp.lang.perl.misc:
> 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
--
$_='Just another Perl hacker'; print +( join( '', map { eval $_; $@ }
'use warnings FATAL => "all"; printf "%-1s", "\n"', 'use strict; a',
'use warnings FATAL => "all"; "@x"', '1->m') =~
m|${ s/(.)/($1).*/g; \ $_ }|is),',';
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Rubyzip - `dup': can't dup NilClass (TypeError) Luka Stolyarov Ruby 10 09-11-2010 12:13 PM
:s.respond_to?(:dup) && :s.dup raises Fran├žois Beausoleil Ruby 1 04-05-2007 05:55 PM
windows and socket.dup gangesmaster Python 0 06-23-2006 11:51 AM
Can 56k auto DUP be enabled for programs running on XP? rt Computer Support 0 02-19-2005 01:43 AM
segfault dup'ing string through C++ (via swig) module David Eger Python 0 07-11-2003 01:55 PM



Advertisments