Re-reading from already read filehandle

前端 未结 2 840
梦毁少年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.

提交回复
热议问题