Perl - 以相反的顺序逐行读取文件

时间:2010-07-10 22:10:59

标签: perl

  

可能重复:
  How can I read lines from the end of file in Perl?

首先读取最后一行,然后读取最后一行,等等。文件太大,无法放入内存。

3 个答案:

答案 0 :(得分:7)

按相反顺序读取行:

use File::ReadBackwards;

my $back = File::ReadBackwards->new(shift @ARGV) or die $!;
print while defined( $_ = $back->readline );

我最初误解了这个问题,并认为你想以交替的方式前后阅读 - 这似乎更有趣。 :)

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->() );

答案 1 :(得分:6)

如果tac可用,则很简单:

#! /usr/bin/perl

use warnings;
no warnings 'exec';
use strict;

open my $fh, "-|", "tac", @ARGV
  or die "$0: spawn tac failed: $!";

print while <$fh>;

自行运行:

$ ./readrev readrev
print while <$fh>;

  or die "$0: spawn tac failed: $!";
open my $fh, "-|", "tac", @ARGV

use strict;
no warnings 'exec';
use warnings;

#! /usr/bin/perl

答案 2 :(得分:3)

我最近使用PerlIO::reverse来做这件事。我更喜欢PerlIO::reverse的IO层而不是File::ReadBackwards提供的自定义对象或绑定句柄界面。