是否可以将参数传递给Perl模块加载? [英] Is it possible to pass parameters to a Perl module loading?

查看:57
本文介绍了是否可以将参数传递给Perl模块加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个多环境的Perl脚本.大家都知道,如果做得不好,环境配置调整可能会很痛苦.由于我的perl脚本必须允许某些命令行参数出于配置值重载的目的,因此我提供了以下解决方案:

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;

因此,以下脚本:

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

将产生下一个输出:

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

重点是我想在Cfg模块加载期间定义$ gEnvironment的值. 这样一来,我便可以在所有环境中使用相同的配置模块.

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.

这可能吗?

推荐答案

我相信您追求的是自定义import方法:

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

package Cfg;

our $gMessage;

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

和其他地方:

use Cfg "some message";

importuse某些模块时perl将调用的内容.有关详细信息,请参见 perldoc -f use .

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

这篇关于是否可以将参数传递给Perl模块加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆