Re: Perl archeology: Need help in refactoring of old Perl code that does not use strict
by Corion (Patriarch) on Nov 14, 2017 at 08:45 UTC
|
In addition to AnomalousMonks advice of a test suite, I would suggest at the very least to invest the time up front to run automatic regression tests between whatever development version of the program you have and the current "good" (but ugly) version. That way you can easily verify whether your change affected the output and operation of the program. Ideally, the output of your new program and the old program should remain identical while you are cleaning things up.
Note that you can enable strict locally in blocks, so you don't need to make the main program compliant but can start out with subroutines or files and slowly convert them.
For your second question, have a look at Exporter. Basically it allows you to im/export subroutine names between packages:
package x;
use Exporter 'import';
our @EXPORT_OK = ('a', 'b', 'c');
#main_script
use x 'a', 'b'; # makes a() and b() available in the main namespace
To find and collect the global variables, maybe it helps you to dump the global namespace before and after your program has run. All these names are good candidates for being at least declared via our to make them visible, and then ideally removed to pass the parameters explicitly instead of implicitly:
#!perl -w
use strict;
our $already_fixed = 1; # this won't show up
# Put this right before the "uncleaned" part of the script starts
my %initial_variables;
BEGIN {
%initial_variables = %main::; # make a copy at the start of the pr
+ogram
}
END {
#use Data::Dumper;
#warn Dumper \%initial_variables;
#warn Dumper \%main::;
# At the end, look what names came newly into being, and tell us a
+bout them:
for my $key (sort keys %main::) {
if( ! exists $initial_variables{ $key } ) {
print "Undeclared global variable '$key' found\n";
my $glob = $main::{ $key };
if( defined *{ $glob }{GLOB}) {
print "used as filehandle *'$key', replace by a lexica
+l filehandle\n";
};
if( defined *{ $glob }{CODE}) {
print "used as subroutine '$key'\n"; # so maybe a fals
+e alarm unless you dynamically load code?!
};
if( defined *{ $glob }{SCALAR}) {
print "used as scalar \$'$key', declare as 'our'\n";
};
if( defined *{ $glob }{ARRAY}) {
print "used as array \@'$key', declare as 'our'\n";
};
if( defined *{ $glob }{HASH}) {
print "used as hash \%'$key', declare as 'our'\n";
};
};
};
}
no strict;
$foo = 1;
@bar = (qw(baz bat man));
open LOG, '<', *STDIN;
sub foo_2 {}
use strict;
The above code is a rough cut and for some reason it claims all global names as scalars in addition to their real use, but it should give you a start at generating a list of undeclared names.
Also see Of Symbol Tables and Globs. | [reply] [d/l] [select] |
|
Thank you. that's a very good advice.
Both the idea to use "strict" pragma selectively and to use Data::Dumper; are simply great !!!
| [reply] |
Re: Perl archeology: Need help in refactoring of old Perl code that does not use strict
by AnomalousMonk (Archbishop) on Nov 14, 2017 at 07:20 UTC
|
I'd like to suggest that you also need a
Step 0: Write a test suite that the current code passes for all normal modes of operation and for all failure modes.
With this test suite, you can be reasonably certain that refactored code isn't just going to be spreading the devastation.
Given that you seem to be describing a spaghetti-coded application with communication from function to function via all kinds of secret tunnels and spooky-action-at-a-distance global variables, I'd say you have a job on your hands just with Step 0. But you've already taken a test suite into consideration... Right?
Give a man a fish: <%-{-{-{-<
| [reply] [d/l] |
|
This is what I would do after 'Step 0':
- identify a function using a global variable.
- verify the global variable does not change during execution of this function, e.g. some other function called by this function modifies it. (insert some code to do this for you)
- convert global variable into an argument and update all callers.
If the variable does change during the run then pick a different function first. When you got the global state disentangled a bit it's a lot easier to reason about what this code is doing. Everything that's still using a global needs to be treated with very careful attention.
| [reply] |
|
| [reply] |
Re: Perl archeology: Need help in refactoring of old Perl code that does not use strict
by 1nickt (Canon) on Nov 14, 2017 at 19:53 UTC
|
Hi,
Since no one has addressed this part...
How can I access subs a,b,c without qualifying them with namespace x from the main:: namespace?
See Exporter or Exporter::Tiny. Also see perlmod.
"main" script:
use strict; use warnings;
use Foo qw/ bar /;
print bar('baz');
__END__
file 'Foo.pm':
package Foo;
use strict; use warnings;
use parent qw/ Exporter /;
our @EXPORT_OK = qw/ bar /;
sub bar { return uc shift }
1;
Hope this helps!
The way forward always starts with a minimal test.
| [reply] [d/l] [select] |
|
Thank you very much. Never heard about existence of Exporter::Tiny. That might help me.
| [reply] |
Re: Perl archeology: Need help in refactoring of old Perl code that does not use strict
by AnomalousMonk (Archbishop) on Nov 14, 2017 at 18:11 UTC
|
Further to Corion's wise general advice, I would add to
... find and collect the global variables ... and then [remove them and] pass the parameters explicitly instead of implicitly ...
that if you can also identify a global variable as, in fact, not varying during program execution, you can convert this variable into a true constant and thus remove a potential headache: a global constant is, in general, a Good Thing (or at least no Bad Thing).
Give a man a fish: <%-{-{-{-<
| [reply] [d/l] |
Re: Perl archeology: Need help in refactoring of old Perl code that does not use strict
by karlgoethebier (Abbot) on Nov 14, 2017 at 19:15 UTC
|
"...any Perl IDE has some of required capabilities..."
Even listing and visualizing vars and so on might be a big relief i guess.
You might take a look at EPIC. But no warranty. I have used Eclipse for refactoring jobs with PHP, ActionScript and Java with varying results: From pretty cool to totally inferior. Unfortunately i don't have any serious experience with the mentioned plugin. You have been warned. Good luck.
Best regards, Karl
«The Crux of the Biscuit is the Apostrophe»
perl -MCrypt::CBC -E 'say Crypt::CBC->new(-key=>'kgb',-cipher=>"Blowfish")->decrypt_hex($ENV{KARL});'Help
| [reply] [d/l] |
Re: Perl archeology: Need help in refactoring of old Perl code that does not use strict (hurry up and wait)
by Anonymous Monk on Nov 14, 2017 at 08:26 UTC
|
1) ... strict pragma ...My time to make the conversion is limited and using some off the shelf tools that speed up the process would be a great help.
Hurry up and leave it alone :)
use strict; itself confers no benefits; The benefits come from avoidance of the bad practices forbidden by strict :)
That pretty much means convert one at a time by hand after you have learned the understanding of importance of knowing :) Speed kills
2. If possible ... I do not understand ...
That is a hint you shouldn't be refactoring anything programmatically.
There are a million nodes on perlmonks, and a readers digest version might be Modern Perl a loose description of how experienced and effective Perl 5 programmers work....You can learn this too.
Hurry up and bone up
3. Generally this task looks like a case of refactoring. I wonder, if any Perl IDE has some of required capabilities, or are there tools that can helpful.
I hope you have foot insurance :) happy hunting :) perlcritic, PPI/PPIx::XPath , PPIx::EditorTools,
App::EditorTools - Command line tool for Perl code refactoring
Code::CutNPaste - Find Duplicate Perl Code
So enjoy, test first, step0++
| [reply] [d/l] [select] |
|
use strict; itself confers no benefits; The benefits come from avoidance of the bad practices forbidden by strict :)
That's very true. But if we are talking about the modernization of legacy code this advice sounds like "it is better to be rich and healthy, than poor and sick" ;-)
The code is valuable and will probably live another 20 years and so leaving it alone is not an optimal solution. And modernization always has resource constrains so it is important not to "overachieve". I chose a very modest goal -- implementing "strict" pragma because "use strict" and "use warnings" are two pragmas which do improve maintainability of Perl scripts. Other new staff mostly don't.
Not to open religious wars, but as for your recommendation to read "Modern Perl" I respectfully reject it because I suspect that chromatic is a "complexity junkie" in heart :-).
So this is an implicit attempt to push me into "overachiever mode". By "overachiever mode" I means conversion of the code using all those fancy idioms available in Perl 5.22 and above and advocated by chromatic, especially unhealthy fascination with OO (inspired by the desire to complete with Python) which I consider counterproductive. When I see bless statement in simple scripts I suspect fraud :-). Also during modernization of legacy code it is important to respect the original author way of thinking and coding.
BTW when they introduced escaping opening curvy brackets in regex in 5.22 (which was a blunder) I thought that now all bets are off and I am staying with teen versions of Perl forever ;-). Later I changed my mind and use 5.26 is some cases, but the problem remains: inability to reduce complexity of the language, only add to it, sometimes screwing previously healthy parts of the language in the process.
| [reply] |
|
So this is an implicit attempt to push me into "overachiever mode". By "overachiever mode" I means conversion of the code using all those fancy idioms available in Perl 5.22 and above and advocated by chromatic, especially unhealthy fascination with OO (inspired by the desire to complete with Python) which I consider counterproductive. When I see bless statement in simple scripts I suspect fraud.
I don't get anything out of it if you read it or don't, but it's a shame that you might give other people the impression that the book tries to do something it was never intended to do. For example, you won't see anything in the book about using:
- Smartmatch (except "don't use this")
- Postfix-dereferencing (because it wasn't explicitly marked as stable for the version supported in 4e)
- Subroutine signatures (again stability)
The book has always been freely available online, in all of its versions. I'm disappointed that you'd write this without having at least skimmed the book for yourself to see if it's true. (It's not.)
| [reply] |
|
| [reply] |
|
|
|
|
Hi
I chose a very modest goal -- implementing "strict" pragma because "use strict" and "use warnings" are two pragmas which do improve maintainability of Perl scripts. Other new staff mostly don't.
You can be strict/warnings compliant and not benefit
Being in a hurry to automate strict/warnings compliance hints that you just might be missing the point of strict/warnings
The slideshow I linked is very good, its called Program Repair Shop , its about refactoring/strict/warnings
So this is an implicit attempt to push me into "overachiever mode".
No, Its an explicit invitation to answer question #2 yourself,
Chapter 9. Managing Real Programs, Modules, Organizing Code With Modules
I'm boning up right now
Its hard being an archeologist
| [reply] |