问题描述
我正在解析格式如下的文本文件
I'm parsing through a text file formatted like below
> alpha
apple
airplane
art
> beta
bear
blue
beat
> charlie
cow
cent
coat
我正在尝试查找具有主题(例如ta")的条目(alpha beta charlie
).如果找到了主题,那么我会尝试打印出每个条目下方的单词(bear blue beat
).所以在这个例子中,我想要以下输出
I'm trying to find entries (alpha beta charlie
) that has a motif (e.g. "ta"). If the motif is found, then I'm trying to print out the words underneath each entry (bear blue beat
).So in this example, I'd like the following output
> beta
bear
blue
beat
我已经知道如何打印输入行,但不知道如何打印下面的行.任何想法将不胜感激.
I've figured out how to print the entry line, but no idea how to print out the lines underneath. Any ideas would be much appreciated.
my $motif = "ta";
my $file = "file.pl";
open(INPUT, $file) or die "Can't open file.\n";
parse($motif);
sub parse{
my ($x) = (@_);
while(<INPUT>){
if($_ =~ />*($x)/){
print $_."\n";
# if($_ !~ />/){
# print $_."\n";
}else{
next;
}
}
}
推荐答案
嗯,你需要保持循环状态.匹配会触发打印"状态,不匹配会触发它.所以你有这样的事情吗?
Well, you need to keep loop state. The match triggers a "print" state, and a mismatch detriggers it. So you have something like this?
sub parse {
my ($x) = (@_);
my $printable = 0
while (<INPUT>) {
if ($_ =~ /^>.*($x)/) {
print $_;
$printable = 1;
} elsif ($_ =~ /^>/) {
$printable = 0;
} elsif ($printable) {
print $_;
}
}
}
这篇关于如何在 Perl 中的正则表达式匹配后打印行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!