Skip to content

Instantly share code, notes, and snippets.

@fgabolde
Created January 5, 2015 13:47
Show Gist options
  • Save fgabolde/5f13469dacc931cba80b to your computer and use it in GitHub Desktop.
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.
#!/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;
@fgabolde
Copy link
Author

fgabolde commented Jan 5, 2015

(doesn't understand scope, so { my $foo = 1; } { my $foo = 1; $foo++ } will happily escape detection)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment