Re-reading from already read filehandle

前端 未结 2 825
梦毁少年i
梦毁少年i 2021-01-01 20:22

I opened a file to read from line by line:

open(FH,\"<\",\"$myfile\") or die \"could not open $myfile: $!\";
while ()
{
    # ...do something
}
         


        
相关标签:
2条回答
  • 2021-01-01 20:56

    Use seek to rewind to the beginning of the file:

    seek FH, 0, 0;
    

    Or, being more verbose:

    use Fcntl;
    seek FH, 0, SEEK_SET;
    

    Please note that it greatly limits the usefulness of your tool if you must seek on the input, as it can never be used as a filter. It is extremely useful to be able to read from a pipe. Keeping in mind that 57% of all statistics are made up, you should realize that 98% of programs that seek on their input do so needlessly. Try very hard to process your data in such a way that you don't need to read it twice. If that is possible, your program will be much more useful.

    0 讨论(0)
  • 2021-01-01 21:02

    You have a few options.

    • Reopen the file handle
    • Set the position to the beginning of the file using seek, as William Pursell suggested.
    • Use a module such as Tie::File, which lets you read the file as an array, without loading it into memory.
    0 讨论(0)
提交回复
热议问题