Perl 搜索功能 [英] Perl seek function

查看:63
本文介绍了Perl 搜索功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题解决了.非常感谢.
我的问题和我使用的解决方案如下所述.

问题:

This problem was solved. Thank you very much.
My question and the solution I am using is stated below.

Question:

open IN, "<./test.txt";
seek(IN,10,0);
read IN, $temp, 5;

seek(IN,20,0);
close(IN);


情况是,我的手柄将从位置 0 开始.
在第一个搜索函数之后,我的文件句柄将位于位置 10.
阅读后,我的手柄将位于位置 15.
这一刻,我再次寻找.然后程序将从头开始或从位置 20 开始查找.
我的问题是无论如何我都可以在文件中进行搜索,这样我就不需要每次都从文件的起点进行搜索?



The situation is that, my handle will start at position 0.
After the first seek function, my file handle will at position 10.
After I read, my handle will at position 15.
At this moment, I seek again. Then the program will seek from the beginning or from position 20.
My question is that is there anyway for me to do searching in a file so that I do not need to search from the starting point of the file every time?


我使用的方式:

The way I am using:

use Fcntl qw(SEEK_SET SEEK_CUR SEEK_END); #SEEK_SET=0 SEEK_CUR=1 ...

$target_byte=30;
open IN, "<./test.txt";
seek(IN,10,SEEK_SET);
read IN, $temp, 5;

$position=tell(IN);
seek(IN,$target_byte-$position,SEEK_CUR);
#do what I want
close(IN);

推荐答案

在我们开始之前,

  • 您要求我们做出的假设毫无意义.第一个字节在位置零.总是.

  • The assumption you ask us to make no sense. The first byte is at position zero. Always.

它被称为文件句柄"(因为它允许您保留文件),而不是文件处理程序"(因为它不处理任何事情).

It's called a "file handle" (since it allows you to hold onto a file), not a "file handler" (since it doesn't handle anything).

如果您使用常量 SEEK_SET、SEEK_CUR 和 SEEK_END 而不是 0、1 和 2,会更清楚.

It would be clearer if you used the constants SEEK_SET, SEEK_CUR and SEEK_END instead of 0, 1 and 2.

然后你的代码是

use Fcntl qw( SEEK_SET );

open IN, "<./test.txt";
seek(IN,10,SEEK_SET);
read IN, $temp, 5;

seek(IN,20,SEEK_SET);
close(IN);

顾名思义,它将位置设置为指定的值.

As the name implies, it sets the position to the specified value.

所以,

  • 第一次搜索后,文件位置为 10.
  • read后,文件位置为15.
  • 第二次搜索后,文件位置为 20.

视觉上,

         +--------------------------  0: Initially.
         |         +---------------- 10: After seek($fh, 10, SEEK_SET).
         |         |    +----------- 15: After reading "KLMNO".
         |         |    |    +------ 20: After seek($fh, 20, SEEK_SET).
         |         |    |    |
         v         v    v    v     
file:    ABCDEFGHIJKLMNOPQRSTUVWXYZ
indexes: 01234567890123456789012345

如果您想相对于您当前的位置进行搜索,您可以使用 SEEK_CUR.

If you wanted to seek relative to your current position, you'd use SEEK_CUR.

         +--------------------------  0: Initially.
         |         +---------------- 10: After seek($fh, 10, SEEK_CUR).
         |         |    +----------- 15: After reading "KLMNO".
         |         |    |         +- 25: After seek($fh, 10, SEEK_CUR).
         |         |    |         |
         v         v    v         v 
file:    ABCDEFGHIJKLMNOPQRSTUVWXYZ
indexes: 01234567890123456789012345

这篇关于Perl 搜索功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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