How do I dup() a filehandle in Perl?

If you check perlfunc/open, you'll see that several of the ways to call open() should do the trick. For example:

    open(LOG, ">>/tmp/logfile");
    open(STDERR, ">&LOG");
Or even with a literal numeric descriptor:

   $fd = $ENV{MHCONTEXTFD};
   open(MHCONTEXT, "<&=$fd");	# like fdopen(3S)
Note that "<&STDIN" makes a copy, but "<&=STDIN" make an alias. That means if you close an aliased handle, all aliases become inaccessible. This is not true with a copied one.

Error checking, as always, has been left as an exercise for the reader.


Back to perlfaq5