-1

下面是代码

$string = "any text
Affected area :
menu

Feature to test :

diagnostics
";

$string1=rindex($string,':');
print "$string1\n";

$string2=substr($string,$string1+1);
print "$string2";

我可以使用上面的代码在“要测试的功能”之后找到字符串,但我想找到用于受影响区域的字符串,例如。菜单。请帮忙

4

2 回答 2

1

我认为这是某种测试程序。这样做会更有意义吗?

use strict;
use warnings;

my $feature_to_test;
my $affected_area;
while ( my $line <DATA> ) {
    chomp $line;
    if ( $line =~ /^Affected area\s*:/i ) {
        for (;;) {  #Loop forever (until I tell you to stop i.e.)
            my $line = <DATA>;
            if ( $line !~ /^\s*$/ ) {
               $affected_area = $line;
               last;
            }
        }
    }
    if ( $line =~ /^Affected area\s*:/i ) {
        for (;;) {  #Loop forever (until I tell you to stop i.e.)
            my $line = <DATA>;
            if ( $line !~ /^\s*$/ ) {
               $affected_area = $line;
               last;
            }
        }
    }
    if ( $line =~ /^Feature to test\s*:/i ) {
        for (;;) {  #Loop forever (until I tell you to stop i.e.)
            my $line = <DATA>;
            if ( $line !~ /^\s*$/ ) {
               $feature_to_test = $line;
               last;
            }
        }
    }

}
else {
    print qq("Not a special line: "$line"\n);
}

__DATA__
any text
Affected area :
menu

Feature to test :

diagnostics

这种方法的优点是它允许您逐行测试,而不是尝试一次解析整个记录。另外,它更好地模拟了文件的读取方式。

也可以用来split将长文本拆分成一个数组,您也可以逐行遍历:

use strict;
use warnings;

my $string = "any text
Affected area :
menu

Feature to test :

diagnostics
";
my @string_list = split /\n/, $string;  #Now, this is split line by line
for my $line ( @string_list ) {
    print "same logic as above...\n";
}

这样做作为一个循环并在每一行中读取会使逻辑更清晰,更容易理解。它可能效率不高,但即使在经济型 PC 上,即使在 Perl 中读取数百万行文件也不会超过几秒钟。

于 2013-01-29T18:39:55.833 回答
0

也许使用积极的后视和捕获的正则表达式在这里会有所帮助:

use strict;
use warnings;

my $string = "any text
Affected area :
menu

Feature to test :

diagnostics
";

my ($area) = $string =~ /(?<=area :\n)(.+)/;

print $area;

输出:

menu
于 2013-01-29T18:01:38.733 回答