slogger has asked for the wisdom of the Perl Monks concerning the following question:

Hi - first post here :-)

I want to read a file thats changing and print the line within that file thats changing - the file isnt being appended to but the lines within the file are changing (hope thats clear!)

I wrote a perl script - works which is good, however as I'm learning perl I'm sure theres a better way of doing this - essentially I'm using a loop, opening file, reading line, extracting data from line, closing file, then sleeping 10 secs then repeating.. instead of doing numerous open/close what would people suggest - I've thought maybe opening, reading then seeking back to start - however that didnt seem to pick updates.. ideas welcome!numpty code follows:-

#!/usr/bin/perl -w # program to print out cumulative interrupt for network device drivers use strict; #use diagnostics; while (1) { open(PFS,"/proc/interrupts")||die "Cant open file $! \n"; while (<PFS>) { if ( $_ =~ "eth" ) { # change print format here .. overlay and have headers print $_; } # seek(PFS,0,1); # print tell PFS; } close(PFS); sleep(10); }
Thanks, Slogger.

Replies are listed 'Best First'.
Re: reading a changing file
by jethro (Monsignor) on Jun 07, 2011 at 13:51 UTC

    Don't worry. Opening a file every 10 seconds is to a CPU like a fly is to a windshield: hardly noticable

    Here a short test:

    time perl -e 'for (1..100000) { open($f,"<","./t7.pl"); close($f); }' real 0m0.446s user 0m0.229s sys 0m0.201s

    So my machine can open and close a file about 250000 times a seconds

Re: reading a changing file
by jethro (Monsignor) on Jun 07, 2011 at 13:49 UTC

    Opening a file every 10 seconds is to a CPU like a fly to a windshield: hardly noticable

    Here a short test:

    time perl -e 'for (1..100000) { open($f,"<","./t7.pl"); close($f); }' real 0m0.446s user 0m0.229s sys 0m0.201s

    So my machine here can open and close a file about 250000 times a seconds

    (This node was reparented from a duplicate question node)

      yep - appreciate that, not so much of a performance question/worry as an 'am I doing this the right way' - i.e. is there a better way of reading a dynamically updating file than the way I am doing it here .. being a beginner more of an educational question really.( also I realise timtowodt! - but some prob better than others)

        Lets say, I would do it the same way.

Re: reading a changing file
by wind (Priest) on Jun 07, 2011 at 16:07 UTC

    Doing multiple open and close statements is the correct way to go here. It clearly documents that the file might be changing in the interim 10 seconds wait.

    You might considering doing a shared read lock using flock, but I doubt that it's a strong need for you nor that the other process would respect it.

      Many thanks - wasnt sure if my method was too brute force and there was a more elegant way to do it!