可能重複:
How can I read lines from the end of file in Perl?的Perl - 逐行讀取文件中的行以相反的順序
首先閱讀的最後一行,然後倒數第二個,等文件太大而不適合記憶。以相反的順序
可能重複:
How can I read lines from the end of file in Perl?的Perl - 逐行讀取文件中的行以相反的順序
首先閱讀的最後一行,然後倒數第二個,等文件太大而不適合記憶。以相反的順序
讀線:
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->());
我最近使用PerlIO::reverse
做了這個。我更喜歡PerlIO::reverse
的IO層,而不是File::ReadBackwards
提供的自定義對象或綁定句柄接口。
簡單,如果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
參見:http://stackoverflow.com/questions/303053/how-can-i-read-lines - 從最末端的文件中-的perl- – kiamlaluno 2010-07-10 22:17:01
聽起來像你正在perl或類似的實現unix trace命令。 – 2010-07-10 22:56:21