reading from line X in perl

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ciary
    Recognized Expert New Member
    • Apr 2009
    • 247

    reading from line X in perl

    hi all,

    i recently encountered a problem about something that should be really easy but in fact i couldn't find any information on how to do it.
    what i want to do is read a logfile in perl. i open the file, read the data, parse it, then close the file. so far so good.
    now, while the script is running, i append a few lines to the logfile. i now want perl to somehow remember at which line it last read, and when i open the file i want to jump to the end and read only the new lines.
    the reason for this is that i might have huge logfiles and reading them completely all the time won't work fast enough.
    Code:
    $exitfile = '/path/to/the_exit_file';
    while (!(-e $exitfile)) {
        print "and we read?\n";
    
        open(DAT, "/path/to/mylog.log") || die("Could not open file!");    
        foreach $line (<DAT>) {
            chomp($line);
            print $line;
        }   
        close(DAT);
        sleep(1);
    }
    in this case, i keep opening the file every second and reading it all the way through until i create a certain file (the exit file)
    anyone know how i can just read the new lines?
    what i was thinking was counting the lines in my foreach loop, but then i have the problem of not being able to move my pointer to that location.
    thanks!
  • Ciary
    Recognized Expert New Member
    • Apr 2009
    • 247

    #2
    forget it, searched for 3 hours, posted this, then 10 minutes later i had a solutions

    Code:
    $exitfile = '/path/to/the_exit_file';
    my $pointerPos = 0;
    while (!(-e $exitfile)) {
        print "and we read?\n";
     
        open(DAT, "/path/to/mylog.log") || die("Could not open file!");    
        seek DAT, $pointerPos, 0;
        foreach $line (<DAT>) {
            print $line;
        }   
        $pointerPos = tell DAT;
        close(DAT);
        sleep(1);
    }
    just "tell" to ask the position in bytes and "seek" to move the pointer back to that position. also the last 0 in seek means you start $pointerPos byes from the START of the file. you can also put seek from the end of the file.

    Comment

    Working...