There is such a warning ("once") for package variables

>perl -c -we"print $a" Name "main::a" used only once: possible typo at -e line 1.

On the p5p list, there was talk of doing something similar for lexical variables. It's a very long thread, so what follows is a highlight.

First, it seems there's no real good reason. Quote demerphq,

Used once warnings are irritating and IMO unnecessary for lexicals.

The reason globals have the warning is that it is easy to make a typo that changes program behaviour without being notified of it any other way.

$Foo::Baar=1; print "Foo::Bar is enabled" if $Foo::Bar;

Strictures will not catch this, in fact, nothing but "used once" errors will catch this.

However notice that under strictures its impossible to construct the same scenario with lexicals as one of the two usages will be an undeclared variable error.

Furthermore, it seems there are too many legit uses of single-use lexical variables to add a warning. Some examples from the thread:

my $foo = 42; eval q[$foo++];
my($unused, $foo) = func();
{ open my $fh, ">$file" or die $! } # touch
{ my $lock = lock_something(); # lock released on scope exit do_stuff_that_needs_the_lock(); }
{ my $tree = ...; my $sentry = Object::Destroyer->new( $tree, 'delete' ); ... }
my $object = bless \do {my $var} => $class;

Due to all the false positives, it seems the general consensus is that the check should done by a linter (e.g. Perl::Critic).


In reply to Re: Warnings on unused variables? by ikegami
in thread Warnings on unused variables? by AZed

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.