Refactoring support: automatic global-to-lexical conversion
|Reported by:||tsee||Owned by:|
|Component:||Refactoring Perl 5||Version:||0.29|
I recently had the non-fun experience of having to refactor a moderately large single-file program that was not strict-clean. No variable declarations anywhere.
In such programs, variables are still usually being used like lexicals. Very few variables are *really* global.
My experience was that getting the program strict clean and declaring all variables lexically in the tightest possible scope went a long way towards making the program more readable and accessible.
The way there, however, was paved with rather tedious hours of work. Therefore, I propose the ultimately useful refactoring feature:
In a similar fashion to the lexical-variable renaming, introduce a feature that finds the tightest scope in which a given variable could be declared lexically and then does so. Of course, this doesn't work for true globals, but honestly, I believe those can be identified rather easily in most cases.
This is not an easy task, however. The lexical rename walks the PPI tree upwards until it finds a scope in which (not including arbitrary sub-scopes, I hope) there is a declaration of the variable. This would have to do something remotely similar, but really the other way around. Starting from the top-level, recurse into all sub scopes and find out whether the variable is used there. If it's only used in one of them, go into that one and rinse, repeat. I'm sure there's something (apart from the trivial "this will be ugly to implement using PPI") I'm missing.
Of course, this feature won't work well for reused variable names such as $i for iteration. But it'd still be a start!