Examples in Perl

Parsing config files

The typical method used to accept configuration details is to define the variables at the beginning of the script and let users modify them if they want to. But, remember the config files for old DOS programs or the .ini iles under Windows ? If you would like to give your users the flexibility of modifying configuration variables in that way, you could use the subroutine given below :

sub parse_config_file {

    local ($config_line, $Name, $Value, $Config);

    ($File, $Config) = @_;

    if (!open (CONFIG, "$File")) {
        print "ERROR: Config file not found : $File";

    while () {
        chop ($config_line);          # Get rid of the trailling \n
        $config_line =~ s/^\s*//;     # Remove spaces at the start of the line
        $config_line =~ s/\s*$//;     # Remove spaces at the end of the line
        if ( ($config_line !~ /^#/) && ($config_line ne "") ){    # Ignore lines starting with # and blank lines
            ($Name, $Value) = split (/=/, $config_line);          # Split each line into name value pairs
            $$Config{$Name} = $Value;                             # Create a hash of the name value pairs



# Call the subroutine
&parse_config_file ($path_and_filename, \%Config);

foreach $Config_key (keys %Config) {

    print "$Config_key = $Config{$Config_key}\n";


This reads the config file mentioned ($path_and_filename) and populates the hash (%Config) with the name value pairs found in the config file.
Blank lines and lines starting with # in the config file are ignored.

If the config file was :

# Description of option1
option1 = value1

# Description of option2
option2 = value2

The hash would be :

Config{option1} = value1
Config{option2} = value2

Back to Table of Contents