如何通过行号(而不是字节)更改文件句柄中指针的位置?
我想将第一行设置为开始读取文件。有什么正确的方法可以做到这一点?
设置文件指针本身并不是目的。如果你想要读取某一行,请使用Tie::File。
use Tie::File qw();
tie my @file, 'Tie::File', 'thefilename' or die $!;
print $file[2] # 3rd line
my $i = 1000; while($i < scalar @file){ print $file[$i]; $i++; }
? - nsbmprint for @file[1000..$#file]
。 - Borodin# make a pass through the whole file to get the position of each line
my @pos = (0); # first line begins at byte 0
open my $fh, '<', $the_file;
while (<$fh>) {
push @pos, tell($fh);
}
# don't close($fh)
# now use seek to move to the position you want
$line5 = do { seek $fh,$pos[4],0; <$fh> };
$second_to_last_line = do { seek $fh,$pos[-3],0; <$fh> };