Subject: | RegularExpressions::ProhibitCaptureWithoutTest flags cases when $1, etc. clearly are set |
The intention of the test RegularExpressions::ProhibitCaptureWithoutTest
is given by page 253 of PBP:
Show quoted text
>Use the numeric capture variables only when you're sure
>that the preceding match succeeded.
One way to check for that is to always use them inside an if-test, but
it's not the only way. Throwing an exception if the regexp match failed
seems an equally good way, especially if you expect it to always match.
This test program
#!/usr/bin/perl
use warnings;
use strict;
use 5.010;
use Carp qw(croak);
my $s = 'abc';
$s =~ /(\w+)/x or croak "bad string '$s'";
say $1;
run through perlcritic -3 produces the warning
test:9:5:Capture variable used outside conditional
[RegularExpressions::ProhibitCaptureWithoutTest] (See page 253 of PBP)
IMHO, the test should not be for 'used outside conditional' but 'used
without checking that the regexp matched'.
perlcritic can't solve the halting problem and cannot determine all
cases where it is certain the regexp matched. So there will always be
some false positives. But it would be a big improvement to note that
testing the return value of the =~ operator and jumping away if false
means that later code can use $1, $2 etc. knowing that the match succeeded.