Subject: | ProhibitUnusedVariables notice readline <$fh> |
Date: | Sat, 05 Feb 2011 10:06:34 +1100 |
To: | bug-Perl-Critic [...] rt.cpan.org |
From: | Kevin Ryde <user42 [...] zip.com.au> |
ProhibitUnusedVariables doesn't seem to know that a readline style
<$foo> is a use of the variable $foo. I get some joy from the change
below.
I struck this in the second .run addition,
open (my $foo, '<', '/etc/motd') or die;
my $line = <$foo>;
I suppose it might also recognise that open(my $foo, ...) initializes
$foo by side-effect, if the intention of the policy is to pick up only
vars which are both uninitialized and then unused. Dunno if that would
be a bit tricky.
Index: lib/Perl/Critic/Policy/Variables/ProhibitUnusedVariables.pm
===================================================================
--- lib/Perl/Critic/Policy/Variables/ProhibitUnusedVariables.pm (revision 4013)
+++ lib/Perl/Critic/Policy/Variables/ProhibitUnusedVariables.pm (working copy)
@@ -41,6 +41,7 @@
my %symbol_usage;
_get_symbol_usage( \%symbol_usage, $document );
_get_regexp_symbol_usage( \%symbol_usage, $document );
+ _get_readline_usage( \%symbol_usage, $document );
return if not %symbol_usage;
my $declarations = $document->find('PPI::Statement::Variable');
@@ -114,6 +115,28 @@
return;
}
+# Look for PPI::Token::QuoteLike::Readline of <$foo>, which is handle $foo
+# being used.
+# Sometimes PPI (as of version 1.213) parses <$foo> as operator '<', symbol
+# $foo, operator '>', eg. "print <$foo>". That's picked up by
+# _get_symbol_usage() above.
+#
+sub _get_readline_usage {
+ my ( $symbol_usage, $document ) = @_;
+
+ my $readlines = $document->find('PPI::Token::QuoteLike::Readline')
+ || return; # if none
+
+ foreach my $readline ( @{$readlines} ) {
+ ### readline content: $readline->content
+ if ($readline->content =~ /^<(\$.*)>$/) {
+ ### add: $1
+ $symbol_usage->{$1}++;
+ }
+ }
+
+ return;
+}
#-----------------------------------------------------------------------------
1;
Index: t/Variables/ProhibitUnusedVariables.run
===================================================================
--- t/Variables/ProhibitUnusedVariables.run (revision 4013)
+++ t/Variables/ProhibitUnusedVariables.run (working copy)
@@ -162,6 +162,24 @@
#-----------------------------------------------------------------------------
+## name Variable used in <$foo> readline
+## failures 0
+## cut
+
+my $foo;
+my $line = <$foo>;
+
+#-----------------------------------------------------------------------------
+
+## name Variable used in open() and <$foo>
+## failures 0
+## cut
+
+open (my $foo, '<', '/etc/motd') or die;
+my $line = <$foo>;
+
+#-----------------------------------------------------------------------------
+
##############################################################################
# $URL$
# $Date$