Created
January 5, 2015 13:47
-
-
Save fgabolde/5f13469dacc931cba80b to your computer and use it in GitHub Desktop.
Use PPI to detect variables that are declared and never referred to again.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
use 5.010; | |
use Carp; | |
use autodie; | |
use utf8; | |
use PPI; | |
# Usage: perl detect-unused-vars.pl FILENAME | |
# e.g. perl detect-unused-vars.pl detect-unused-vars.pl | |
my $filename = shift; | |
# the example reports this line | |
my ($foo, $bar); | |
my $document = PPI::Document->new($filename); | |
# get all variable declarations | |
my %declarations = map { my $decl = $_; map { $_ => $decl } $_->symbols } @{$document->find(sub { | |
my (undef, $elt) = @_; | |
$elt->isa('PPI::Statement::Variable') && $elt->type eq 'my'; | |
})}; | |
foreach my $declaration (keys %declarations) { | |
my $references = $document->find(sub { | |
my (undef, $elt) = @_; | |
$elt->isa('PPI::Token::Symbol') && $elt->symbol eq $declaration; | |
}); | |
if (@{$references} <= 1) { | |
# only referred to once, presumably in the declaration | |
say sprintf('%s:%d:%d %s only referred to once', | |
$filename, | |
$declarations{$declaration}->line_number, | |
$declarations{$declaration}->column_number, | |
$declaration); | |
} | |
} | |
exit 0; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(doesn't understand scope, so { my $foo = 1; } { my $foo = 1; $foo++ } will happily escape detection)