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 ?
You can pass various arguments to a Perl subroutine like you do in any other programming language and they can be accessed inside the function using the special array @_. Thus the first argument to the function is in [0],thesecondisin_[1], and so on.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With