从已经读取的文件句柄重新读取 [英] Re-reading from already read filehandle

查看:47
本文介绍了从已经读取的文件句柄重新读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打开一个文件逐行读取:

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
}

并意识到就好像文件中的控件位于 EOF 并且不会从文件的第一行开始迭代......这是默认行为吗?如何解决这个问题?文件很大,我不想作为数组保留在内存中.那么我唯一的选择是关闭并再次打开文件吗?

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?

推荐答案

使用seek回退到文件开头:

Use seek to rewind to the beginning of the file:

seek FH, 0, 0;

或者,更详细:

use Fcntl;
seek FH, 0, SEEK_SET;

请注意,如果您必须搜索输入,它会极大地限制您的工具的实用性,因为它永远不能用作过滤器.能够从管道中读取是非常有用的,您应该努力安排您的程序,以便不需要查找.

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, and you should strive to arrange your program so that the seek is not necessary.

这篇关于从已经读取的文件句柄重新读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆