如何使用 perl 回退一行

发布于 2024-10-11 06:49:21 字数 105 浏览 3 评论 0原文

谁能告诉我当你迭代文本文件时,如何在 Perl 中返回一行。例如,如果我看到行中的文本并且我认识到它,并且如果它被识别为特定模式,我想回到上一行做一些事情并进一步继续。

提前致谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

丶情人眼里出诗心の 2024-10-18 06:49:21

通常,您不会返回,只需跟踪上一行:

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

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;
}
七婞 2024-10-18 06:49:21
my $prevline = '';
for my $line (<INFILE>) {

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

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

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

    $prevline = $line;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文