Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

regex - 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
";
        }
} 

I have above regex to split some string into array. It works fine.

Problem is :

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Perl Critic doesn't give any errors. It gives policy violations.

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;
    }

To fix the second one, just change /.../ to m{...}.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...