Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Config file

by cajun (Chaplain)
on Nov 20, 2005 at 08:05 UTC ( [id://510215]=perlquestion: print w/replies, xml ) Need Help??

cajun has asked for the wisdom of the Perl Monks concerning the following question:

What is the best (most simple) module for reading values from a config file?

I have maybe a dozen variables that I want to remove from three related scripts. The config file would be something along the lines of:

$variable1 = '/somedirectory/';
$variable2 = '/someotherdirectory/';
$variable3 = '/yetanother/directory/';
etc....

Update: Thanks to all for the many different ways to accomplish the goal !!

Replies are listed 'Best First'.
Re: Config file
by davido (Cardinal) on Nov 20, 2005 at 08:08 UTC
Re: Config file
by Zaxo (Archbishop) on Nov 20, 2005 at 09:07 UTC

    That format looks like legal perl, so it can be as simple as: do 'config.file';.

    As it is, that won't survive strict, so you need to declare your variables. They will need to be in the symbol table because lexicals have file scope, and do FILE's cannot see lexicals from the caller.

    An example:

    $ cat >cfg.pl $foo='/foodir/'; $bar='/bardir/'; $baz='/baz/dir/'; $ cat >cfg #!/usr/bin/perl my ($foo,$baz); do 'cfg.pl'; print $foo,$/; print $bar,$/; print $baz,$/; $ chmod 755 cfg $ ./cfg /bardir/ $
    The lexicals $foo and $baz mask the global versions, but global $bar is seen.

    Changing the lexical my line to use vars qw/$foo $bar $baz/;, and useing strict and warnings, we get

    $ ./cfg /foodir/ /bardir/ /baz/dir/ $
    It's tempting to make the config file more independent by declaring its variables within it, but forcing users to know the names will prevent nasty namespace collisions.

    After Compline,
    Zaxo

      The modern way of globalizing the variables that are set in the do "config" is to declare them with our rather than use vars.
      perlcapt
      -ben
Re: Config file
by GrandFather (Saint) on Nov 20, 2005 at 08:33 UTC
Re: Config file
by rcseege (Pilgrim) on Nov 20, 2005 at 15:59 UTC

    I like Config::Properties which is very similar to the java.util.Properties class. It allows for reading/writing of a file with the folowing formats:

    # This will get ignored ! This will also get ignored variable1: /somedirectory variable2: /someotherdirectory variable3 = /yetanotherdirectory variable4: This is a longer than usual \ property value

    It ignores blank lines and comments, can recognize = or : as a separator, and can deal with multiline properties. It's pretty easy to use, and handles most simple situations well. This would likely be my first choice.

    XML is generally not my first choice for config files, but usually the next step once they start to become less simple and my configuration file needs to be able to cope with a complex configuration where a tree might be useful. XML files are easy for a user who is hand-editing to mess up. I'll second GrandFather's recommendation of XML::Simple but only for those cases that I can't address with a simpler solution.

    Many of the other configuration file suggestions that I've seen mentioned I might use if I had no control of the configuration file format that I was reading: Unix passwd file formats, Win32 ini files, etc.


    Updated: Huh.. Somehow, I missed AppConfig. Nice one, davidrw - I like it. I think between Config::Properties, AppConfig, and XML-Simple those would cover any of my needs
Re: Config file
by Nomad (Pilgrim) on Nov 20, 2005 at 11:57 UTC

    In addition to the modules already mentioned, Config::Auto is also pretty cool.

Re: Config file
by davidrw (Prior) on Nov 20, 2005 at 12:34 UTC
    I'll toss out a mention of AppConfig was well.. handles a lot of different formats including Win32-style "ini" files.
Re: Config file
by PerlingTheUK (Hermit) on Nov 20, 2005 at 10:00 UTC
    Config::Simple would be my first choice. Your "config"-code looks a bit like actual Perl content though and you might just want to read the file and eval each line.

    Cheers,
    PerlingTheUK
Re: Config file
by dave0 (Friar) on Nov 20, 2005 at 13:21 UTC
    Another choice worth mentioning is to use a YAML file as a config file.
      If you're going to use YAML, you might as well go whole hog and use YAML::AppConfig... which I use for everything myself...

        Well, I'm in an environment where I can't install modules; I have to use whatever's in the installation. In my case, that's YAML::XS. I make do. ;-)

Re: Config file
by Random_Walk (Prior) on May 16, 2013 at 11:35 UTC

    This is a rather old thread but I stumbled across it looking for ideas for a config file format so I thought I would update it for future journeymen. For my config files I have settled on JSON, which I guess was not around when this thread was hewn from stone tablets. To make it easier for humans I have used relaxed (allow comments and terminal commas) and pretty options for when I output them.

    use strict; use warnings; use JSON; use Data::Dumper; # Get a JSON object to handle our config file and data stores my $json = JSON->new->relaxed->pretty; # Read configuration my $cfg; # open my $config, '<', $conf_file or die "Can not read $conf_file: $! +\n"; local $/; $cfg = $json->decode (<DATA>); close $config; print Dumper $cfg; __DATA__ # Here is our config # There are many like it but this one is ours { ##################################################### # # # Data Base connections strings and active option # # # ##################################################### "DB_Connections" : { "foo" : { "conx" : [ "dbi:Oracle:FOO.world", "foo_user", "foo_pswd" ], "active" : 1 }, "bar" : { "conx" : [ "dbi:DB2:bar", "bar_user", "bar_pass", ], "active" : 0 } }, "hosts" : ( "host1" : ["readme", "andme"], "host2" : ["readthis", "that", "and another"], # comma allowed b +y relaxed ) }

    Cheers,
    R.

    Pereant, qui ante nos nostra dixerunt!

      Seriously, everyone? More than 90% of config files are simple and can be processed in two lines of code (not counting formatting). Like this...open a file, and parse the lines with a map:

      open( my $config_fh, '< :encoding(UTF-8)', '/some/path/.tofile' ) or die "$0: Can't open config file. $!\n"; my %creds = map { $_ =~ /(\S+)\s*?:\s*?(\S+)/ } <$config_fh>;

      This will hande those simple key/value config lines:

      key: value

      But at the end of the day, I would also say "standardize on a common CPAN module..."

        I like that this was the issue that fired you up enough to create your first node, just now, from an account created in 2008. (credit to LanX for noticing)

      ...and in my mind, this is the one to use for simple configs:

          Config::Simple->import_from('myconf.cfg', \%Config);

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://510215]
Approved by davido
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (3)
As of 2024-03-29 05:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found