Yet another stupid mistake #2: my oh my

Stricture helps me catch some typos by requiring predeclaration of variables (e.g. using the lexical my()). But it doesn't warn me about my stupidity. In this month alone, I have been bitten by two episodes of sloppy refactoring, where I left an extra 'my' on an inner block, something like:

my $foo = blah();
...
for (...) {
    my $foo = ...;
    ...
    # we lost what we've done to the inner $foo
}

Of course, -w and 'use strict' didn't help me here. -w only warns about the second 'my' if done in the same scope. And so around half an hour were spent chasing these two silent bugs. I guess a critic policy could be written for this sort of thing, e.g. forbidding two lexical declaration inside the same sub. And discipline yourself to keep paragraphs of code relatively short.

5 Comments

A Perl::Critic policy for this actually exists: Variables::ProhibitReusedNames :)

warnings::unused also catches that :)

Leave a comment

About Steven Haryanto

user-pic A programmer (mostly Perl 5 nowadays). My CPAN ID: SHARYANTO. I'm sedusedan on perlmonks. My twitter is stevenharyanto (but I don't tweet much). Follow me on github: sharyanto.