tags:

views:

73

answers:

2

Hello,

I am currently developping a multi-environment perl script. As you all know, environment configuration juggling could be quite a pain if badly done. As my perl script must allow some command line parameters in a configuration value overload purpose, i came with the following solution :

package Cfg;
use strict;
use warnings;
my $gEnvironment = "DEBUG";#"PRODUCTION";
my %gConfig = (
  DEBUG=>{MESSAGE=>"This is a dbg env.",URL=>"www.my-dbg-url.org"},
  PRODUCTION=>{MESSAGE=>"This is a prod env.",URL=>"www.shinyprodurl.org"}
);
my $gMessage = defined $gConfig{$gEnvironment} ?
  $gConfig{$gEnvironment}{MESSAGE} : die "Crappy environment";
sub Message { $gMessage = shift(@_) if (@_); $gMessage }
sub Url {
  defined $gConfig{$gEnvironment} ?
    $gConfig{$gEnvironment}{URL} : die "Crappy environment"
}
1;

So, the following script :

use strict;
use warnings;
use Cfg;
print Cfg::Message,"\n";
Cfg::Message("I'm a surcharged message.");
print Cfg::Message;

Would produce the next output:

This is a dbg env.
I'm a surcharged message.

The point is I want to define $gEnvironment's value during the loading of the Cfg module. This would allow me to use the same configuration module in all my environments.

Is this possible ?

+8  A: 

I believe a custom import method is what you're after:

package Cfg;

our $gMessage;

sub import {
    my ($package, $msg) = @_;
    $gMessage = $msg;
}

and somewhere else:

use Cfg "some message";

import is what perl will call when you use some module. Please see perldoc -f use for the details.

rafl
+4  A: 

Here is how to accomplish what you want but I think you would be better served by going the full object-oriented route. The solution below would only need a few modifications to achieve that:

package Cfg;

use strict; use warnings;
use Carp;

my $gEnvironment = "DEBUG"; # default
my $gMessage;

my %gConfig = (
    DEBUG => {
        MESSAGE => "This is a dbg env.",
        URL => "www.my-dbg-url.org",
    },
    PRODUCTION => {
        MESSAGE => "This is a prod env.",
        URL => "www.shinyprodurl.org",
    },
);

sub import {
    my $pkg = shift;
    my ($env) = @_;

    if ( defined $env ) {
        unless ( $env eq 'PRODUCTION'
                or $env eq 'DEBUG' ) {
            croak "Invalid environment '$env'";
        }
        $gEnvironment = $env;
    }
    $gMessage = $gConfig{$gEnvironment}{MESSAGE};
    return;
}

sub Message {
    ($gMessage) = @_ if @_;
    return $gMessage;
}

sub Url {
    return $gConfig{$gEnvironment}{URL};
}


1;

And, to use it:

#!/usr/bin/perl

use strict; use warnings;

use Cfg qw( PRODUCTION );

print Cfg::Message,"\n";
Cfg::Message("I'm a surcharged message.");

print Cfg::Message;
Sinan Ünür