#!/usr/bin/perl -w use strict; use File::Basename; my $cfgfile = "/datapath/filename.cfg"; my %settings = readConfigData( $cfgfile ); my $novalues = scalar( keys( %settings ) ); # Since we're done with the file name; reuse the var ( $cfgfile ) = fileparse( $cfgfile ); print "The $cfgfile file contains ", "the following settings and values:\n\n", map { " $_ = $settings{ $_}\n" } sort keys %settings; print "\n", "$novalues settings were found in all."; sub readConfigData # -------------------------------------------------------------- # Returns a hash containing setting names and values from the # configuration file. Note that the name of the configuration # file is passed as the first parameter. # -------------------------------------------------------------- { my $filename = shift; # name of the config file. my $filedata = ""; # holds a line read from the file my %settings = (); # holds results returned to caller my $cfglabel = ""; # holds name of a setting my $cfgvalue = ""; # holds value of a setting open( DATAFILE, "< $filename" ) or die "Can't Open $filename; reason: $!\n"; while ( ) { chomp; $filedata = trim( $_ ); # save line into var. # ignore comments and blank lines if ( ( substr( $filedata, 0, 1 ) eq '#' ) or ( $filedata eq "" ) ) { next; } else # it looks like data, so split it up, trim # white space and save it into the hash. { ( $cfglabel, $cfgvalue ) = split( /=/ ); $cfglabel = trim( $cfglabel ); $cfgvalue = trim( $cfgvalue ); $settings{ $cfglabel } = $cfgvalue; } } close( DATAFILE ) or die "Can't Close $filename; reason: $!\n"; return %settings; } sub trim # -------------------------------------------------------------- # Removes white space from either side of a value. Used in a few # places. # -------------------------------------------------------------- { my $value = shift; $value =~ s/^\s+//; # trim leading white space $value =~ s/\s+$//; # trim trailing white space return $value }