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

Hi all, I have to process a simple textfile line by line, which I knew how to do.
But after the line has been read (and some operations has been done) I want to delete it from the file.
How can I do this?

What do I need this for:
A textfile with a listing of files on the filesystem is given to my script. On each record I do some operations. If the script fails I knew when/where the script stopped and I just restart it with the remaining list . . .
Regards Alex
  • Comment on How to delet the actual readed line from a file?

Replies are listed 'Best First'.
Re: How to delet the actual readed line from a file?
by Corion (Patriarch) on Aug 04, 2008 at 11:38 UTC

    The easiest way is to keep the line but store the line number in the file you last processed.

    The second easiest way is to use Tie::File and treat the file like an array.

Re: How to delet the actual readed line from a file?
by Bloodnok (Vicar) on Aug 04, 2008 at 13:07 UTC
    Hi ,

    Pls correct me if I'm wrong, but it strikes me that, by inference, the application must have persistence to some degree, hence maybe something like this might better fit the bill (apologies in advance for untested code)...

    # Slurp file in one - assuming there's room:-) open FILE, "<fname" or die "open() - $!"; local undef $/; @files = <FILE> close FILE; while (@files) { # # do something with file $_ # shift @files; } END { # Save any state @files && do { open FILE, ">fname" or die "Cannot save state - $!"; printf FILE "@files"; close FILE; }; }
    HTH , Rgds ,

    A user level that continues to overstate my experience :-))
Re: How to delet the actual readed line from a file?
by pjotrik (Friar) on Aug 04, 2008 at 12:37 UTC
    I'd suggest a reverse approach - to another file, print the lines already successfully processed. Then you know where the processing stopped (and you can get the rest using diff).
Re: How to delet the actual readed line from a file?
by gokuraku (Monk) on Aug 04, 2008 at 11:44 UTC
    An alternate way, much like already suggested, is to read the file in as an array then use shift to pull the first line off the array and output the rest to the same or a new filename.