如何用perl返回一行

问题描述 投票:2回答:2

任何人都可以告诉我,当你遍历文本文件时,在Perl中返回一行是怎么回事。例如,如果我看到文本在线并且我认出它并且如果它被识别为特定模式我想回到前一行做一些事情并继续进行。

提前致谢。

regex perl line
2个回答
13
投票

通常你不回去,你只需跟踪上一行:

my $previous; # contents of previous line
while (my $line = <$fh>) {
    if ($line =~ /pattern/) {
        # do something with $previous
    }
    ...
} continue {
    $previous = $line;
}

使用continue块可以保证即使您通过next绕过部分循环体也可以复制。

如果你想真正倒带,你可以用seektell来做,但它更麻烦:

my $previous = undef;    # beginning of previous line
my $current  = tell $fh; # beginning of current line
while (my $line = <$fh>) {
    if ($line =~ /pattern/ && defined $previous) {
        my $pos = tell $fh;      # save current position
        seek $fh, $previous, 0;  # seek to beginning of previous line (0 = SEEK_SET)
        print scalar <$fh>;      # do something with previous line
        seek $fh, $pos,  0;      # restore position
    }
    ...
} continue {
    $previous = $current;
    $current  = tell $fh;
}

7
投票
my $prevline = '';
for my $line (<INFILE>) {

    # do something with the $line and have $prevline at your disposal

    $prevline = $line;
}
© www.soinside.com 2019 - 2024. All rights reserved.