在Perl IO::File中设置要读取的行

3

如何通过行号(而不是字节)更改文件句柄中指针的位置?

我想将第一行设置为开始读取文件。有什么正确的方法可以做到这一点?


我已经尝试过谷歌搜索,但没有找到答案。我不想使用tell、seek、sysseek等字节级别的指针设置方式,而是希望以行号的方式轻松实现。如果您知道如何做,请回答一下。 - nsbm
2
除非您处理的文件每行都具有相同数量的字节,否则您如何仅通过行号设置位置呢? - user554546
[facepalm] 答案是:你不知道。你没有足够的信息。 - user554546
2个回答

8

设置文件指针本身并不是目的。如果你想要读取某一行,请使用Tie::File

use Tie::File qw();
tie my @file, 'Tie::File', 'thefilename' or die $!;
print $file[2]  # 3rd line

这将整个文件内容读入名为file的变量中,如果我没记错的话。问题是:如果文件非常大,有人想要从末尾读取两行,那么需要将整个文件加载到内存中,然后获取所需的行,还是有更好的方法? - Lajos Arpad
1
那么从任意行读取到结尾的最佳方法是遍历数组吗?例如:my $i = 1000; while($i < scalar @file){ print $file[$i]; $i++; } - nsbm
1
谢谢您的回答,我对Perl一窍不通,但我对任何技术问题都很感兴趣。如果我在之前的评论中提出的问题很琐碎,我深表歉意。 - Lajos Arpad
2
@nsbm:是的,或者print for @file[1000..$#file] - Borodin

4
使用tell和seek来读写文件中每一行的位置。以下是一种可能的解决方案,需要你遍历整个文件,但不需要一次完全将文件加载到内存中:
# 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> };

@posзј“еӯҳжҳҜж ёеҝғжЁЎеқ—Tie::FileеҶ…йғЁзҡ„е·ҘдҪңеҺҹзҗҶгҖӮ - daxim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接