任何人都可以告诉我,当你遍历文本文件时,在Perl中返回一行是怎么回事。例如,如果我看到文本在线并且我认出它并且如果它被识别为特定模式我想回到前一行做一些事情并继续进行。
提前致谢。
通常你不回去,你只需跟踪上一行:
my $previous; # contents of previous line
while (my $line = <$fh>) {
if ($line =~ /pattern/) {
# do something with $previous
}
...
} continue {
$previous = $line;
}
使用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;
}
my $prevline = '';
for my $line (<INFILE>) {
# do something with the $line and have $prevline at your disposal
$prevline = $line;
}