Perl Script to Read a Config File

Post Info: 5,202 views 0 Comments Post a comment

Perl script to read a config and store the values in Hash which can be accessed in the script.

#!/usr/local/bin/perl

# Check the Arguments
if ($#ARGV != 0 ) {
    print "Usage: $0 <ConfigFile>\n";
    exit;
}

my $config_file=$ARGV[0];
my %Config = ();

# Function to Parse the Environment Variables
sub parse_config_file {
    local ($config_line, $Name, $Value, $Config);
    my ($File, $Config) = @_;
    open (CONFIG, "$File") or die "ERROR: Config file not found : $File";
    while (<CONFIG>) {
        $config_line=$_;
        chop ($config_line);          # Remove 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
        }
    }
    close(CONFIG);
}

# Source Env Variables
print "Starting Script $0\n";
print "Source Variables From Config File : $config_file \n";

parse_config_file ($config_file, \%Config);  # Call the Function to create the Config hash

# Print the key value pair from the Config Hash
for my $key ( keys %Config ) {
    my $value = $Config{$key};
    print "$key => $value\n";
}

print "Script $0 Finished\n";

Here is the sample Config File

# Config Variables

# Directory and File
Process_Dir=/var/process/
Data_Dir=/mnt/

# DB User
DB_Host=localhost
DB_Name=test
DB_User=test

#EmailIds
Email_Ids=someone\@example.com

Return to top

Leave a Reply

 

Are you finished?

Return to top