Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

duping a filehandle

by smackdab (Pilgrim)
on Jan 14, 2007 at 03:52 UTC ( #594600=perlquestion: print w/replies, xml ) Need Help??
smackdab has asked for the wisdom of the Perl Monks concerning the following question:

I am writing a script that will parse different types of log files and I want to have a template for the different log files...So I thought the main program would open a log file, I would then call each template and it would make a copy of the filehandle (instead of a new open) and then read the header and determine if it was for that template to handle...
use strict; use warnings; sub GetLogHeader { open(TEMPLOG, "<&LOG"); while (my $row = <TEMPLOG>) { print "$row\n"; last; } close(TEMPLOG); } my $abc; open(LOG, "c:\\log.log") || die; $abc = <LOG>; my $header = GetLogHeader(\*LOG); $abc = <LOG>; $abc = <LOG>;
Basically I can't figure out how to pass a filehandle and then copy it. I expect that the copy can move the filepointer w/o affecting the original filehandle, but I can't really figure that out either...In this test, it seems that LOG and TEMPLOG are equal and I really want them to be able to point to different parts of the log file... I am just getting back in to Perl and am quite rusty ;-)

Replies are listed 'Best First'.
Re: duping a filehandle
by ikegami (Pope) on Jan 14, 2007 at 03:58 UTC

    From the man page for dup (on FreeBSD):

    The object referenced by the descriptor does not distinguish between oldd and newd in any way. Thus if newd and oldd are duplicate references to an open file, read(2), write(2) and lseek(2) calls all move a single pointer into the file, and append mode, non-blocking I/O and asynchronous I/O options are shared between the references. If a separate pointer into the file is desired, a different object reference to the file must be obtained by issuing an additional open(2) system call. The close-on- exec flag on the new file descriptor is unset.

    (Emphasis mine)

    Look into tell + seek instead of duping.

      THANKS!!! I wish I knew unix better...I found a "seek($fh_log, 0, 0);" before returning from my subroutine put the filepointer back at the top, so all is good!
        Alternatively, pass just the filename to your sub and open it there using a different file handle (preferably lexical).

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://594600]
Approved by ikegami
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2017-08-16 17:37 GMT
Find Nodes?
    Voting Booth?
    Who is your favorite scientist and why?

    Results (271 votes). Check out past polls.