perl中seek函数的用法(2009-09-10 16:22:47)
seek 设置文件的当前位置!
当一个文件非常大时可以从指定位置读起。
seek FILEHANDLE,POSITION,WHENCE
成功返回真,失败返回假。
POSITION 是读入的新位置(字节)。
WHENCE有3个值,0表示新位置是POSITION,1表示当前位置加上POSITION,2表示文件尾加上POSITION
例如:从file.txt的12字节开始读起并打印出来。
open (FILEHANDLE,"seek FILEHANDLE,12,0;
while (){
print;
}
close (FILEHANDLE);
例子:
Read Line And Selected Subsequent Lines
#!/usr/bin/perl
open (TEST, "while () {
if (index ($_, "keyword") > -1) {
$position = tell(TEST);
$keyword_line = $_;
$line_1 = ;
$line_2 = ;
$line_3 = ;
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__