加载中…
个人资料
菜鸟
菜鸟
  • 博客等级:
  • 博客积分:0
  • 博客访问:10,868
  • 关注人气:812
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

perl中seek函数的用法

(2009-09-10 16:22:47)
标签:

perl

seek

用法

杂谈

分类: perl语言学习
seek 设置文件的当前位置!
当一个文件非常大时可以从指定位置读起。
seek FILEHANDLE,POSITION,WHENCE   
成功返回真,失败返回假。
POSITION 是读入的新位置(字节)。
WHENCE有3个值,0表示新位置是POSITION,1表示当前位置加上POSITION,2表示文件尾加上POSITION
例如:从file.txt的12字节开始读起并打印出来。
open (FILEHANDLE,"<file.txt") or die "cannot open file.txt";
seek FILEHANDLE,12,0;
while (<FILEHANDLE>){
        print;
}
close (FILEHANDLE);
 
例子:
 
Read Line And Selected Subsequent Lines
http://www.purlgurl.net/%7Epurlgurl/graphics/aniline.gif
#!/usr/bin/perl

open (TEST, "<E:/test.txt");
while (<TEST>) {
   if (index ($_, "keyword") > -1) {
    $position = tell(TEST);
    $keyword_line = $_;
    $line_1 = <TEST>;
    $line_2 = <TEST>;
    $line_3 = <TEST>;
    print " $keyword_line $line_1 $line_2 $line_3\n\n";
    if (!($line_1)) { print " __End Of File__"; last; }
    if (!($line_2)) { print " __End Of File__"; last; }
    if (!($line_3)) { print " __End Of File__"; last; }
    seek(TEST, $position, 0);
   }
}
close (TEST);
exit;


test.txt:

skip this line
A keyword is here
print this line
Trick location of keyword
print this line
print this line
print this line
skip this line
skip this line
This is another keyword
print this line
print this line
print this line
skip this line
Last line and a keyword

 

 

PRINTED RESULTS:

A keyword is here
 print this line
 Trick location of keyword
 print this line


 Trick location of keyword
 print this line
 print this line
 print this line


 This is another keyword
 print this line
 print this line
 print this line


 Last line and a keyword
 
 

 __End Of File__

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有