arraysregexperlsplitperl-critic

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

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)

Solution

  • 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.