Friday, June 5, 2009

Make your config files very flexible (w/ Perl eval)

I have to make my config files flexible so that I can allow my users a lot of options and even override functions. I can do this by making my config file "eval"-able. Meaning that the config file is actually Perl code that can be interpreted by the calling Perl script.

Most of the code was taken from:

http://www.usenix.org/publications/perl/perl13.html

Here is my proof of concept code:

##### FILE: evalConfigExample.pl #####


#!/usr/bin/perl -w
# Filename: evalConfigFileExample.pl
# This is a proof of concept script to show how one can use a perl script as a config.
# file. This allows much more freedom when declaring a configuration file. One can
# call functions, redefine functions and generally do anything that you could.
# normally do in a regular perl script. Ex:
#; ~/bin/evalConfigFileExample.pl -file ~/bin/evalConfigFileExample.cfg

use Getopt::Long;
use Data::Dumper;
use Pod::Usage;

my $page_info ;
my %opts = ();
my $ok = GetOptions(\%opts,
'file=s',
'help'
);
if ( !$ok ) { die; }
pod2usage(1) if (exists ( $opts{help} ) );

sub printer {
print "In Perl prog\n";
}

sub hello_world {
print "Calling hello_world from eval'd config file!\n";
}

sub parse_cfg {
my($file) = @_;
delete($INC{$file});
eval('require("$file")');
die "*** Failed to eval() file $file:\n$@\n" if ($@);
print ("VENDOR = $VENDOR \n");
}

printer();
parse_cfg( $opts{file} );
print ("VENDOR = $VENDOR \n");
printer();

##########################################
# END OF FILE
##########################################



##### FILE: evalConfigExample.cfg #####


#evalConfigFileExample.cfg
$VENDOR = "Sun";
$HARDWARE = "Sparc";
$OS = "Solaris";
$VERSION = "2.5";
$HOSTNAME = `/bin/hostname`;
$PSCMD = "/usr/bin/ps -ef";
hello_world();

sub printer {
print "In required file\n";
}

##########################################
# END OF FILE
##########################################



The output should look like this:


> evalConfigFileExample.pl -file evalConfigFileExample.cfg
In Perl prog
Subroutine printer redefined at evalConfigFileExample.cfg line 9.
Calling hello_world from eval'd config file!
VENDOR = Sun
VENDOR = Sun
In required file

No comments:

Post a Comment