Perl seek function

牧云@^-^@ 提交于 2019-11-30 15:31:22

Before we start,

  • 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).

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

Your code is then

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.

So,

  • After the first seek, the file position will be 10.
  • After the read, the file position will be 15.
  • After the second seek, the file position will be 20.

Visually,

         +--------------------------  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

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