Subject: | Suggested policy: while (<$fh>) inside subroutine |
The following subroutine looks harmless enough:
sub count_lines {
my $filename = shift;
open my $fh, '<', $filename or die;
my $count = 0;
while (<$fh>) {
++$count;
}
return $count;
}
However it is not safe to use in general because it will trample on the caller's $_. This is an easy mistake to make, because the more common foreach (...) is safe and won't affect the caller's $_. The somewhat less common while (<$fh>) construct looks like it works similarly to foreach (...) but has this hidden side effect.
Perlcritic should warn about use of while (<$fh>) in a subroutine unless $_ has been explicitly localized first.