Perl评论家使用正则表达式将字符串拆分为数组时出错 [英] Perl critic error on splitting string into array using regexp
问题描述
sub func {
my ($n) = @_;
return unless ($n);
my @array;
push @array, $1 while $n =~ /
((?:
[^(),]+ |
( \(
(?: [^()]+ | (?2) )*
\) )
)+)
(?: ,\s* | $)
/xg;
return \@array;
}
for my $item (@array) {
if (index($item, '$n') != -1) {
print "HELLO\n";
}
}
我在regex上面有将一些字符串拆分成数组的方法。
I have above regex to split some string into array. It works fine.
问题是:
Perl评论家给出了以下错误。请告知我该如何解决。
Perl critic gives below errors. Please advise how do i fix this.
Capture variable used outside conditional at line 150,
near 'push @array, $1 while $n =~ /'. (Severity: 3)
Use '{' and '}' to delimit multi-line regexps at line 150,
near 'push @input_expression, $1 while $n =~ /'. (Severity: 1)
String *may* require interpolation at line 168,
near '$item, '$n''. (Severity: 1)
推荐答案
Perl评论家没有给出任何错误。
Perl Critic doesn't give any errors. It gives policy violations.
要解决第一个问题,请将循环从修饰符更改为普通while循环并命名变量:
To fix the first one, change the loop from modifier to normal while loop and name the variable:
while ($n =~ /
...
/xg) {
my $match = $1;
push @array, $match;
}
要修复第二个,只需更改 /。 ../
到 m {...}
。
To fix the second one, just change /.../
to m{...}
.
使用您不太了解的政策毫无意义。有时,可能有很好的理由打破其中的一些理由。盲目地跟随Perl评论家(尤其是在更严厉的水平)不会为您带来任何收益。
In my opinion, it makes little sense to use policies you don't understand well. Sometimes, there might be very good reasons to break some of them; blindly following Perl Critic (especially at more stern levels) doesn't bring you anything.
这篇关于Perl评论家使用正则表达式将字符串拆分为数组时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!