Re-reading from already read filehandle

六眼飞鱼酱① 提交于 2019-11-29 17:30:29

问题


I opened a file to read from line by line:

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

Later on in the program, I try to re-read the file (walk thru the file again):

while (<FH>)
{
    # ...do something
}

and realized that it is as if the control within file is at the EOF and will not iterate from first line in the file.... is this default behavior? How to work around this? The file is big and I do not want to keep in memory as array. So is my only option is to close and open the file again?


回答1:


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.




回答2:


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.


来源:https://stackoverflow.com/questions/12043592/re-reading-from-already-read-filehandle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!