1

我正在学习 perl,现在我试图同时填充几个变量,从匹配捕获中,在一段时间组中。我有“长”版本的工作,如下所示:

$pc = ...
while ($pc =~ m/bla1(.*?)bla2(.*?)bla3(.*?)bla4(.*?)bla5(.*?)bla6(.*?)bla7/g) {
    $var1 = $1; 
    $var2 = $2;
    $var3 = $3;
    $var4 = $4;
    $var5 = $5;
    $var6 = $6;
    ...
}

对于单个捕获(在while循环之外),我知道我可以这样做:

my $string = 'abcde';
my @captures = $string =~ m/.(.)(.)(.)./;
my ($aa,$ab,$ac) = @captures;
print ("$aa - $ab - $ac\n");

有没有办法一次填充while循环中的所有变量?我需要做类似下面的代码的事情,还是有更简单的(不需要2个正则表达式)方法?

while ($pc =~ m/bla1(.*?)bla7/g) {
    my @captures = $1 =~ m/(.*?)bla2(.*?)bla3(.*?)bla4(.*?)bla5(.*?)bla6(.*?)/;
    ($var1,$var2,$var3,$var4,$var5,$var6) = @captures;
    ...
}

提前致谢。

4

2 回答 2

6

好吧,你可以使用

while ($pc =~ m/bla1(.*?)bla2(.*?)bla3(.*?)bla4(.*?)bla5(.*?)bla6(.*?)bla7/g) {
    my ($var1, $var2, $var3, $var4, $var5, $var6) = ($1, $2, $3, $4, $5, $6);
    ... $var3 ...
}

或者

while ($pc =~ m/bla1(.*?)bla2(.*?)bla3(.*?)bla4(.*?)bla5(.*?)bla6(.*?)bla7/g) {
    my @vars = ($1, $2, $3, $4, $5, $6);
    ... $vars[2] ...
}

或者

sub captures { map substr($_[0], $-[$_], $+[$_] - $-[$_]), 1..$#- }

while ($pc =~ m/bla1(.*?)bla2(.*?)bla3(.*?)bla4(.*?)bla5(.*?)bla6(.*?)bla7/g) {
    my @vars = captures($pc);
    ... $vars[2] ...
}

或者

sub captures { no strict 'refs'; map $$_, 1..$#- }

while ($pc =~ m/bla1(.*?)bla2(.*?)bla3(.*?)bla4(.*?)bla5(.*?)bla6(.*?)bla7/g) {
    my @vars = captures();
    ... $vars[2] ...
}

或者

while ($pc =~ m/bla1(?<var1>.*?)bla2(?<var2>.*?)bla3(?<var3>.*?)bla4(?<var4>.*?)bla5(?<var5>.*?)bla6(?<var6>.*?)bla7/g) {
    ... $+{vars3} ...
}
于 2013-07-26T14:09:40.573 回答
0

尝试:

$pc = ...
while ( my @captured = $pc =~ m/bla1(.*?)bla2(.*?)bla3(.*?)bla4(.*?)bla5(.*?)bla6(.*?)bla7/g) {
于 2013-07-26T18:09:43.467 回答