gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 14:35:34 25 4
gpt4 key购买 nike

Possible Duplicate:
How can I read lines from the end of file in 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->() );

关于Perl - 以相反顺序逐行读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3221008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com