Perl - 以相反的顺序逐行读取文件 [英] Perl - reading a file line by line in reverse order
本文介绍了Perl - 以相反的顺序逐行读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
如何从末尾读取行Perl 中的文件?
先读取最后一行,然后再读取最后一行,依此类推.文件太大,无法放入内存.
First read the last line, and then the last but one, etc. The file is too big to fit into memory.
推荐答案
逆序阅读:
use File::ReadBackwards;
my $back = File::ReadBackwards->new(shift @ARGV) or die $!;
print while defined( $_ = $back->readline );
我最初误读了这个问题,并认为您想以交替方式向后和向前阅读——这似乎更有趣.:)
I misread the question initially and thought you wanted to read backward and forward, in alternating fashion -- which seems more interesting. :)
use strict;
use warnings;
use File::ReadBackwards ;
sub read_forward_and_backward {
# Takes a file name and a true/false value.
# If true, the first line returned will be from end of file.
my ($file_name, $read_from_tail) = @_;
# Get our file handles.
my $back = File::ReadBackwards->new($file_name) or die $!;
open my $forw, '<', $file_name or die $!;
# Return an iterator.
my $line;
return sub {
return if $back->tell <= tell($forw);
$line = $read_from_tail ? $back->readline : <$forw>;
$read_from_tail = not $read_from_tail;
return $line;
}
}
# Usage.
my $iter = read_forward_and_backward(@ARGV);
print while defined( $_ = $iter->() );
这篇关于Perl - 以相反的顺序逐行读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文