Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Reading and Writing Perl Config Files

by jdhedden (Deacon)
on Jun 07, 2005 at 15:55 UTC ( #464358=snippet: print w/ replies, xml ) Need Help??

Description: These snippets illustrate the following:
Configuration data is aggregated in hashes (just one for these snippets) to cut down on the number of variable names.
The configuration hashes are maintained in their own namespace to avoid collisions.
Configuration files are maintained in Perl syntax for easy reading, writing and syntax verification.
By maintaining config data in a hash, you can not only quickly access key-value pairs, but also maintain more complex data. For example,
%CFG = (
    'servers' => {
        'SRV1' => {
            'IP'     => 99.32.4.0,
            'user'   => 'aname',
            'pswd'   => 'p4ssw0rd',
            'status' => 'unavailable'
        },
        'SRV2' => {
            'IP'     => 129.99.10.5
            'user'   => 'guest',
            'pswd'   => 'guest'
            'status' => 'unavailable'
        }
    },
    'timeout' => 60,
    'log' => {
        'file'  => '/var/log/my_log.log',
        'level' => 'warn',
    },
    'temp' => 'remove me'
);
Maintaining config data in Perl syntax makes it easy to read:
# Read a configuration file
#   The arg can be a relative or full path, or
#   it can be a file located somewhere in @INC.
sub ReadCfg
{
    my $file = $_[0];

    our $err;

    {   # Put config data into a separate namespace
        package CFG;

        # Process the contents of the config file
        my $rc = do($file);

        # Check for errors
        if ($@) {
            $::err = "ERROR: Failure compiling '$file' - $@";
        } elsif (! defined($rc)) {
            $::err = "ERROR: Failure reading '$file' - $!";
        } elsif (! $rc) {
            $::err = "ERROR: Failure processing '$file'";
        }
    }

    return ($err);
}

# Get our configuration information
if (my $err = ReadCfg('my_cfg.cfg')) {
    print(STDERR $err, "\n");
    exit(1);
}
The config data is easy to access in its own namespace:
# Add last access time
$CFG::CFG{'servers'}{'SRV1'}{'last_access'} = time();

# Change server availablility
$CFG::CFG{'servers'}{'SRV1'}{'status'} = 'online';

# Delete temporary data
delete($CFG::CFG{'temp'});

# Open log file
my $LOG;
if (! open($LOG, "> $CFG::CFG{'log'}{'file'}")) {
    print(STDERR "ERROR: Failure opening log file: $!\n");
    exit(1);
}
The Data::Dumper module lets you write config data easily:
use Data::Dumper;

# Save configuration data
#   Use the same arg as used with ReadCfg()
#   so that file can be found in the %INC.
sub SaveCfg
{
    my $file = $INC{$_[0]};

    my $CFG;
    if (! open($CFG, "> $file")) {
        return ("ERROR: Failure opening '$file' - $!");
    }

    print $CFG <<_MARKER_;
#####
#
# My configuration file
#
#####

use strict;
use warnings;

our (%CFG);

# The configuration data
@{[Data::Dumper->Dump([\%CFG::CFG], ['*CFG'])]}
1;
# EOF
_MARKER_

    close($CFG);
    return (undef);   # Success
}

# Save our configuration file
if (my $err = SaveCfg('my_cfg.cfg')) {
    print(STDERR $err, "\n");
    exit(1);
}
The syntax of the config file can be easily checked using:
perl -c my_cfg.cfg
Comment on Reading and Writing Perl Config Files
Select or Download Code
Re: Reading and Writing Perl Config Files
by fmerges (Chaplain) on Jun 24, 2005 at 12:22 UTC
    Hi,

    Personally I prefer to use YAML for configuration files.

    Update: I think it's silly that someone give -- points for this contribution. Why? Because:

    • I'm not telling nothing wrong about the posting.
    • I think that it's a nice piece of code.
    • But I still recommend for config files YAML because of:
      # YAML documents are very readable by humans.
      # YAML interacts well with scripting languages.
      # YAML uses host languages' native data structures.
      # YAML has a consistent information model.
      # YAML enables stream-based processing.
      # YAML is expressive and extensible.
      # YAML is easy to implement.
      

    So, please, take a look at the website before giving -- points

    Regards,

    |fire| at irc.freenode.net
Re: Reading and Writing Perl Config Files
by chanio (Priest) on Sep 04, 2005 at 03:27 UTC
    Thank you very much,jdhedden for this excelent lesson of OO use of this basic config file style!

    I agree that there are several interesting aproaches to standarize config files. I also prefer the Apache config way. OTH, I should better prefer an XML way. I know.

    But this is similar to what I use in my personal config files. And in this OO way, I won't feel guilty when keeping on doing so, programatically. It is error prone!

    I should only point out that it is not possible to keep a special order in the variables, because of the hash nature of these config files.

    But it is Ok for me and my scripts :)

    { \ ( ' v ' ) / }
    ( \ _ / ) _ _ _ _ ` ( ) ' _ _ _ _
    ( = ( ^ Y ^ ) = ( _ _ ^ ^ ^ ^
    _ _ _ _ \ _ ( m _ _ _ m ) _ _ _ _ _ _ _ _ _ ) c h i a n o , a l b e r t o
    Wherever I lay my KNOPPIX disk, a new FREE LINUX nation could be established
      The trouble with this is that config files are not always 100% "trusted" sources of information. Other processes may write to them. I would reccommend to anyone reading this, at the very least.
      use Safe; my $comp = new Safe; $comp->reval($config_file);
      Instead of just "do" on a config file This gets you, at least, a modicum of protection from your own errors. (Other than that, though, I'm gonna use this code right now...)
        Hi,

        I'm trying to apply code and have problems. Would kindly ask for help.

        I have this in Log.conf :
        # Defines logging groups in terms of room: if device's room maatches r +oom name or if device name is listed separately in hash, then is logg +ed into same log: %Log_rooms = ( "gallery" => { 'BM_shutts_south_00' => 1, 'BM_shutt_no +rth_00' => 1 }, "kitchen" => { }, "office" => { }, "living" => { }, "utility" => { }, "kurilnica" => {}, "lobby" => { }, "toilet" => { } );


        I'd like to read that hash definition into Perl program :
        use Data::Dumper; use Safe; my %Log_rooms; my $config_file ="./Log.conf"; if (-e $config_file) { print "File Exists!"; # my $comp = new Safe; # my $return =$comp->reval($config_file); my $return = do $config_file ; warn "couldn't parse $config_file: $@" if $@; warn "couldn't do $config_file: $!" unless defined $return; warn "couldn't run $config_file" unless $return; } else { %Log_rooms = ( "default" => { 'BM_shutts_south_00' => 1, 'BM_shutt_no +rth_00' => 1 } ); }; print "############################################################### +#################\n"; print Data::Dumper::Dumper(%Log_rooms);


        but I don't get anything in %Log_rooms (default works if config file is missing).

        I'd also like to implement safer way with using Safe, but it also doesn't work. I'd kindly ask for some help...

        Thanks in advance,

        Rob.

Back to Snippets Section

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://464358]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (9)
As of 2014-08-23 17:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (176 votes), past polls