Refactoring is the task of changing code to make it more readable, more maintainable, while not changing it's behavior at all.

The simplest example I usually give is that of changing a variable name to be meaningful.

We all know that naming things is really hard so when we write code and we read in some data we can easily start using meaningless variables. For example $x, $data, or $temp. We might finish our implementation, the code starts doing what we expected it to do, but we still have these meaningless variables.

When a few days or month later we need to come back to make changes we'll be baffled by the meaning of these variables.

It is better to change them to something meaningful to make it easier to read and understand the code.

The process of these changes is called refactoring. In this series of articles we are going to see how to do that.


There are many tasks we need to do before and during refactoring. Let's list a few that later will tackle.

  • Write unit and integration tests.
  • Set up Continuous Integration (CI) to run the tests.
  • Check and monitor code coverage of your tests.
  • Use Perl::Critic to locate areas that need improvement.
  • Go over all the .pl and .pm files in a given directory and list all the functions declared in all the files (Limitations of this approach).
  • List all the functions that are *not called* in any other file. (What about function called from other projects?)
  • Explicit import: Replace the "use Module;" statement by a "use Module qw(func1 func2 func3);" statement in every file listing only the functions that are use in that file.
  • Renaming a variable. Making sure we only replace based on scope and not based on text so if we have the same variable name used in two functions, or even just two blocks, we will replace only the selected one of them.
  • Rename a function and all the places it is being called.
  • Extract subroutine: Take a selected set of lines of code, move them to a newly created function. Place a function call instead of the code we moved. Make sure the variables used in the function are passed in as parameters.


Some of the tools that can be used for refactoring Perl code.

Related Articles