我正在尝试阅读两个关键字之间的文本。虽然不是很有效。我要阅读的是问答,然后将其打印出来。它不起作用,只是继续打印出一个很大的循环。
#!/usr/bin/perl
use strict ;
use warnings;
my $question ;
my $answer ;
while(my $line = <>){
chomp $line ;
if ($line =~ /questionstart(.*)questionend/) {
$question = $1 ; }
elsif ($line =~ /answerstart(.*)answerend/) {
$answer = $1 ; }
my $flashblock = <<"FLASH" ;
<!-- BEGIN -->
<p class="question">
$question
</p>
<p class="answer">
$answer
</p>
<!-- END -->
FLASH
print $flashblock ;
}
这是文件的样本
questionstart
hellphellohellohello
questionend
answerstart
hellohellohello
answerend
最佳答案
正如其他人指出的那样,当您一次读取一行输入文件时,多行正则表达式将永远无法工作。
这是Perl“触发器”操作符(..
)的完美用法。
#!/usr/bin/perl
use strict;
use warnings;
my ($question, $answer);
while (<DATA>) {
if (/questionstart/ .. /questionend/ and ! /question(start|end)/) {
$question .= $_;
}
if (/answerstart/ .. /answerend/ and ! /answer(start|end)/) {
$answer .= $_;
}
# If we're at the end of an answer, do all the stuff
if (/answerend/) {
q_and_a($question, $answer);
# reset text variables
$question = $answer = '';
}
}
sub q_and_a {
my ($q, $a) = @_;
print <<"FLASH";
<!-- BEGIN -->
<p class="question">
$question
</p>
<p class="answer">
$answer
</p>
<!-- END -->
FLASH
}
__DATA__
questionstart
hellphellohellohello
questionend
answerstart
hellohellohello
answerend
更新:将显示移到子例程中以使主循环更干净。