in reply to Indent, anonymous sub, or lexical sub for module private code?

I quite regularly write subs that are called only once (e.g. to read a param file and load it into a param hash). Granted, it does not look quite right if you consider that the main point of a sub is to avoid code duplication (the DRY principle), but it is still better IMHO than having hundreds of code lines in the main section of the program. Having a sub to isolate parts of the program that have a well defined purpose is perfectly legitimate in my view, even if called only once (or twice).

Otherwise, if you really want your function to be private, then use an anonymous sub. If not, the leading underscore convention should be sufficient (you can also use caller to check that the sub is called by only another specific function and no other, but that's seems to be overkill in most cases).

  • Comment on Re: Indent, anonymous sub, or lexical sub for module private code?
  • Download Code

Replies are listed 'Best First'.
Re^2: Indent, anonymous sub, or lexical sub for module private code?
by AppleFritter (Vicar) on Aug 01, 2014 at 10:36 UTC

    Granted, it does not look quite right if you consider that the main point of a sub is to avoid code duplication (the DRY principle), but it is still better IMHO than having hundreds of cole lines in the main section of the program. Haqving a sub to isolate part of the program that have a well defined purpose if perfectly legitimate in my view, even if called only once (or twice).

    I wholeheartedly agree. Although code reuse is an important motivation for subroutines, it's not the only one: it's equally important to be able to break up a program into smaller pieces that carry out a specific task. This makes it easier for the developer to understand the program: each individual subroutine will be easier to digest by virtue of its smaller size, and the main program will be written in a more abstract fashion, allowing the developer to focus on the bigger picture without constantly getting bogged down in details.

    I sometimes think of the developer as the general commanding an army, and the tools the language provides as the individual foot soldiers. Subroutines are the ranks in between, officers and NCOs, allowing the general to say e.g. "fortify this position" without having to care about how exactly this is accomplished (by building trenches), or how trenches are built (by having the foot soldiers dig), or indeed about picking up a spade and moving soil from here to there.