-
use strict;
-
-
open(FH,") or die "$!";
-
my ($one,$two);
-
while (<FH>){ #while[1]
-
$one=$. if /AA/;
-
$two=$. if /BB/;
-
}
-
print "$one", "$two";
-
-
seek (FH,0,0); #关键
-
-
$.=0; #关键
-
-
while (<FH>){ #while[2]
-
print if(1..4); #打印FH文件的第1至4行, #语句1
-
#等同于($.>=1 && $.<=4)。《大骆驼》中说到。
-
}
-
-
close FH;
解析:
1)假如没有seek行,则while[2]不会执行。当第1个while执行完毕后,文件指针已指向
的尾部,不会再执行while[2]。为解决这个问题,利用seek。
2)删除"$n.=0;"这行代码,然后将语句1改成 "print $." ,检查$.的结果。你会发现"$."并非从"1"开始递增!因为使用seek后,while[2]中的$.延续while[1]中的$.递增。若要使while[2]的$.从"1"开始变化,加上一句"$.=0;"就OK了。
3)seek用法详见
seek FILEHANDLE,POSITION,WHENCE
FILEHANDLE 文件句柄
POSITION 移动的字节数,正数向后移动,负数往回移动
WHENCE 值可为0或1或2。The values for WHENCE are 0 to set the new position in bytes to POSITION; 1 to set it to the current position plus POSITION; and 2 to set it to EOF plus POSITION, typically negative.
4)延伸:tell函数返回文件句柄的当前位置,如上面tell(FH);
阅读(3158) | 评论(0) | 转发(0) |