开发者

How to go one line back with perl

开发者 https://www.devze.com 2023-02-03 15:02 出处:网络
Could anybody tell me how it is possible in perl to go one line back in perl when you iterate over the text file. In instance if I see text in line and I recognize it and if it is recognized as an par

Could anybody tell me how it is possible in perl to go one line back in perl when you iterate over the text file. In instance if I see text in line and I recognize it and if it is recognized as an particular pattern I would like go back to 开发者_运维知识库previous line do some stuff and proceed further.

Thanks in advance.


Normally you don't go back, you just keep track of the previous line:

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

The use of a continue block guarantees that the copy is made even if you bypass part of the loop body via next.

If you want to truly rewind you can do it with seek and tell but it's more cumbersome:

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;
}


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

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

    $prevline = $line;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消