Skip to content

Instantly share code, notes, and snippets.

@Grinnz
Created November 28, 2018 19:00
Show Gist options
  • Save Grinnz/ff83724ac482a8255c31d561adcb07ef to your computer and use it in GitHub Desktop.
Save Grinnz/ff83724ac482a8255c31d561adcb07ef to your computer and use it in GitHub Desktop.
package Perl::Critic::Policy::VariableNameReuse;
use strict;
use warnings;
use Perl::Critic::Utils qw(:severities :classification :ppi);
use parent 'Perl::Critic::Policy';
use constant EXPL => 'Using the same name for multiple types of variables can be confusing, e.g. %foo and $foo. Use different names for different variables.';
sub supported_parameters { () }
sub default_severity { $SEVERITY_LOW }
sub default_themes { () }
sub applies_to { 'PPI::Document' }
sub violates {
my ($self, $elem) = @_;
my $symbols = $elem->find('PPI::Token::Symbol') || [];
my @violations;
my %seen;
foreach my $symbol (@$symbols) {
my $actual = $symbol->symbol;
next if $actual =~ m/::/; # ignore globals for now
next if $actual =~ m/^[\$\@%&*](_|[0-9]+|\^\w|\{\^.*\})$/; # skip special variables
(my $name = $actual) =~ s/^.//;
push @{$seen{$name}}, $symbol;
}
foreach my $name (keys %seen) {
my %each_actual;
foreach my $symbol (@{$seen{$name}}) {
$each_actual{$symbol->symbol} //= $symbol;
}
if (keys %each_actual > 1) {
my @symbols = sort { (($a->logical_line_number // 0) <=> ($b->logical_line_number // 0))
|| (($a->visual_column_number // 0) <=> ($b->visual_column_number // 0)) } values %each_actual;
push @violations, $self->violation("Reuse of variable name for $_", EXPL, $_) for @symbols;
}
}
return @violations;
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment