Writing Configuration Files in Perl
It is often useful to have a configuration file for a program, where you can specify certain variables that are used in the program. Examples of configuration parameters might include files, email addresses, usernames, or passwords the program uses, etc. If your Perl program needs to read a configuration file, there are lots of ways to do it.
The most obvious solution is to create a new configuration file syntax. This means you have to write a routine to read the file and parse it, looking for the information needed to control how your program will behave. And for each program you write, you’ll likely have to do it all over again.
You could get a little more clever and write a Perl module that manages the configuration file, and use that with all of your programs that need such a file. However, you still have the problem that the user who has to edit the file will need to learn the syntax you are using, and your module will have to be clever about enforcing that syntax. It’s not an easy problem to parse text written by humans.
So the next option you might consider would be XML. Yes, XML is meant to solve just this problem. But XML for configuration files can be very tedious to maintain, and loading the XML parser just for that purpose is overkill for what is probably a very simple configuration file.
But Perl itself has a very powerful parser built into it. Why not use that? Just write your configuration file using Perl syntax. There are lots of ways of doing it. Here’s one of the simplest…
If your project is called MyApp, then create a file called MyApp/Config.pm and put your configuration there. In MyApp/Config.pm put something like this:
%MyApp::Config = (
email => 'wrw@bayview.com', # editor's note: added missing comment 5/6/2008
file => '/var/log/httpd/access.log',
# ... etc.
);
Then all you need to do is "use MyApp::Config;" and access the hash %MyApp::Config (e.g., $MyApp::Config{email}) in your program. If there’s a syntax error, Perl will give the appropriate error message automatically. What could be simpler?

The example is missing a single quote:
Currently:
email => wrw@bayview.com‘,
Should be:
email => ‘wrw@bayview.com’,
Comment by Dave — May 3, 2008 @ 2:59 pm
Thanks. I edited the post to fix it.
Comment by William Ward — May 6, 2008 @ 9:49 am