Search code examples
perlrequiresubroutine

Is it advisable or not, to separate all the common subroutines in another file in perl?


I want to separate all the common subroutines in another file to save up some space and to tidy up each files. Then just use require() to call a subroutine.

for ex.

sub greet{
     print "Hi there\n";
}

which I added and called in Script1.pl, Script2.pl and Script3.pl.

What are the pro's and con's on separating subroutines to another file?

I'm sorry for my grammar. Hope you'd help me understand.


Solution

  • Whenever you have code that is used by more than one script, it generally ought to be split into a library, as you have described. There are many ways to do this, and each has its own advantages and disadvantages which are beyond the scope of your specific question.

    So to address your specific question as to pros and cons of moving functionality into a library, lets start with

    Pros

    1. Because you have less duplicate code it is easier to
      • Debug your code (fewer places for bugs to exist)
      • Update your code (you don't have to edit the same functionality in 10 places)
    2. It makes it easier to share your library functions with other people, or just other projects
    3. It encourages better design, by making you think modularly
    4. Saves space (a pretty minor point, with modern storage media)

    Cons

    1. It's harder to distribute your code--you must make sure you distribute all required files as well.
    2. It's not as easy to see your entire code at once--only an issue for small projects, where you even have the option of fitting the entire project on the screen (or in your head) at once

    General rule of thumb: Except for very small and/or self-contained projects, use libraries.