Commenting initialization sections
The initialization sections should be logically and physically separate from the beginning of the program, by virtue of extra comments or being at the beginning of the file, for example. Initialization sections, as opposed to the program's beginning described above, contain actual code that executes when the program starts up. In Perl, the initialization section should consist of the following (preferably in that order):
- Modules and pragmas
- BEGIN/END/INIT/CHECK subroutines
- Initialization code
Modules and pragmas
use keyword in Perl directs the interpreter to either load a module or turn
a pragma on ("no pragma" turns a pragma off). Pragmas nudge the
interpreter in the right direction. For example,
use utf8 tells the interpreter to prepare for UTF-8 encoded data files and streams.
It's good to line up the comments for each module horizontally and to have one comment per module or pragma:Listing 5
After the first time you do this, it's just a matter of copy and paste to get the modules and pragmas into a new program. I recommend the "strict" pragma. Among other things, it will ensure that you are honest about declaring your variables, which in my experience is as much a source of bugs in Perl as memory allocation is in C/C++.
See all module and pragma documentation with the perldoc command. For example,
perldoc strict tells all about the strict pragma -- what it does, how to use it, and so on.
Some editors have the nice ability to always place comments at a certain position (in Emacs, the indent-for-comment command does this automatically). Thoroughly familiarize yourself with your editor's commands. It is time well spent.
Although you can view constants as just another Perl pragma, they deserve their own section. Commenting for them should be like that of modules and pragmas, but it looks nice if the arrows line up as well:Listing 6
Comment the BEGIN/END/INIT/CHECK subroutines (see
for more information on them) just like regular subroutines. Creation
can be anywhere in the file, and it's possible to define them multiple
times. I recommend placing them at the beginning or end of the file,
where finding them can be easy. Note that a one-line BEGIN function
does not need extensive commenting.
Last in the initialization section comes the actual code. Again, line the comments up if possible within individual blocks.Listing 8
This initialization code turns auto-flushing on (so output will show up immediately), then tells the
Data::Dumper module to produce human-readable output, and finally creates an AppConfig configuration.