dup a lexical filehandle

Discussion in 'Perl Misc' started by xhoster@gmail.com, Feb 11, 2006.

  1. Guest

    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

    --
    -------------------- http://NewsReader.Com/ --------------------
    Usenet Newsgroup Service $9.95/Month 30GB
     
    , Feb 11, 2006
    #1
    1. Advertising

  2. Anno Siegel Guest

    <> 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),',';
     
    Anno Siegel, Feb 11, 2006
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. David Eger
    Replies:
    0
    Views:
    401
    David Eger
    Jul 11, 2003
  2. gangesmaster

    windows and socket.dup

    gangesmaster, Jun 23, 2006, in forum: Python
    Replies:
    0
    Views:
    320
    gangesmaster
    Jun 23, 2006
  3. Ray Buck
    Replies:
    1
    Views:
    359
  4. François Beausoleil

    :s.respond_to?(:dup) && :s.dup raises

    François Beausoleil, Apr 5, 2007, in forum: Ruby
    Replies:
    1
    Views:
    114
    Tim Hunter
    Apr 5, 2007
  5. Luka Stolyarov
    Replies:
    10
    Views:
    313
    Thomas Sondergaard
    Sep 11, 2010
Loading...

Share This Page