dsollen
dsollen

Reputation: 6459

perl configuration file which contains variables?

I want to create a perl configuration file. I want a file format which has variables. So something like this:

DefaultDirectory = /var/myProgram/
OutputDirectory = $DefaultDirectory/output
InputDirectory = $DefaultDirectory/input

This seems simple, but I'm not sure what is available with perl. The perl ini options I see don't appear to support it. I looked into YAML, but it seems almost overkill.

Can anyone suggest a good file format and CPAN module that supports it which can support simple variables? I'm stuck with perl 5.5 so hopefully an older module.

Upvotes: 0

Views: 1672

Answers (2)

George Adams
George Adams

Reputation: 458

Try Config::General.

test.cfg

# Simple variables
DefaultDirectory = /var/myProgram
OutputDirectory  = $DefaultDirectory/output
InputDirectory   = $DefaultDirectory/input

# Blocks of related variables
<host_dev>
    host     = devsite.example.com
    user     = devuser
    password = ComeOnIn
</host_dev>

<host_prod>
    host     = prodsite.example.com
    user     = produser
    password = LockedDown
</host_prod>

test.pl

#!/usr/bin/perl

use strict;
use warnings;

use Config::General;

my $conf = Config::General->new(
    -ConfigFile => 'test.cfg',
    -InterPolateVars => 1
);

my %config = $conf->getall;

print <<HERE;
    Default directory: $config{'DefaultDirectory'}
    Output directory: $config{'OutputDirectory'}  
    Input directory: $config{'InputDirectory'}    

    Development host: $config{'host_dev'}{'host'}
    Development password: $config{'host_dev'}{'password'}

    Production host: $config{'host_prod'}{'host'}
    Production password: $config{'host_prod'}{'password'}
HERE

Output:

Default directory: /var/myProgram
Output directory: /var/myProgram/output
Input directory: /var/myProgram/input

Development host: devsite.example.com
Development password: ComeOnIn

Production host: prodsite.example.com
Production password: LockedDown

Upvotes: 1

Sobrique
Sobrique

Reputation: 53478

Have you considered just writing your own perl module that contains config?

Something like (MyConfig.pm):

package MyConfig;
our $DefaultDirectory = '/path/to/somewhere';
our $setting_for_something = 5; 

1;

You can then import that with use MyConfig;. You may need to set use lib or FindBin to find the module first though (depends on where you invoke the script - use will search cwd).

But really - perl 5.5? That's .... well worth updating, given that's the version from 2004. I do hope you don't run too much stuff on 10 year old software - the world has changed A LOT in the intervening time. (And so has Perl)

Upvotes: 0

Related Questions