任何人都可以告诉我,当你遍历文本文件时,在Perl中返回一行是怎么回事.例如,如果我看到文本在线并且我认出它并且如果它被识别为特定模式我想回到前一行做一些事情并继续进行.
提前致谢.
Mic*_*man 13
通常你不回去,你只需跟踪上一行:
my $previous; # contents of previous line
while (my $line = <$fh>) {
if ($line =~ /pattern/) {
# do something with $previous
}
...
} continue {
$previous = $line;
}
Run Code Online (Sandbox Code Playgroud)
continue即使您绕过循环体的一部分,块的使用也可以保证复制next.
如果你想真正倒带,你可以用它来做seek,tell但它更麻烦:
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;
}
Run Code Online (Sandbox Code Playgroud)
my $prevline = '';
for my $line (<INFILE>) {
# do something with the $line and have $prevline at your disposal
$prevline = $line;
}
Run Code Online (Sandbox Code Playgroud)