A Perl configuration file example

Here’s some Perl code that I just pulled from a working program that demonstrates how to read a human-readable configuration file in a Perl program:

# do what's needed to read in the configuration file.                                   #
# see the bottom of this url (http://www.perl.com/pub/a/2003/08/07/design2.html?page=3) #
my $config_file = $ARGV[0];
open CONFIG, "$config_file" or die "Program stopping, couldn't open the configuration file '$config_file'.\n";
my $config = join "", <CONFIG>;
close CONFIG;
eval $config;
die "Couldn't interpret the configuration file ($config_file) that was given.\nError details follow: $@\n" if $@;

As you can see from that code segment, the name of the configuration file is passed into this Perl program as the first argument on the command line.

The configuration file

Here are a few (slightly modified) lines from the configuration file that this program reads:

# basic properties #
$var_dir               = '/opt/devdaily/ftplogger/var';
$fifo_file             = '/opt/devdaily/ftplogger/bin/fel.fifo';

$daemon_mode           = 'true';
$debug_mode            = 'true';

$leading_path_test     = '^/foo/bar/baz/';
$our_username          = '^foobar$';
$good_file_extensions  = '\.eps$|\.ps$|\.pdf$';

As you can see, I like this approach because the format of this configuration file is very easy for a human to read and maintain.

Another cool thing about this approach is that it makes the variable names that are used in the configuration file available in your Perl program. For example, in my Perl program I can access the $var_dir variable that is defined in my configuration file. That’s very cool.