在Perl中,是否可以基于字符串创建全局变量?
例如,如果我有这样的功能:
sub create_glob_var {
my ($glob_var_str) = @_;
# something like this ( but not a hash access).
our ${$glob_var_str};
};
我称之为:
create_glob_var( "bar" );
我怎么能修改create_glob_var来实际创建一个名为$bar的全局变量?
我的项目使用的是perl 5.8.5.
编辑
以下不起作用:
use strict;
BEGIN {
sub create_glob_var {
my ($glob_var_str) = @_;
no strict 'refs';
$$glob_var_str = undef; # or whatever you want to set it to
}
create_glob_var("bah");
};
$bah = "blah";
生产:
Variable "$bah" is not imported at /nfs/pdx/home/rbroger1/tmp2.pl line 12. Global symbol "$bah" requires explicit package name at /nfs/pdx/home/rbroger1/tmp2.pl line 12. Execution of /nfs/pdx/home/rbroger1/tmp2.pl aborted due to compilation errors.
注意我意识到使用全局变量会导致ozone depletion and male pattern baldness.我正在尝试清理一些已经完全被全局变量感染的遗留代码.一次一个重构……
解决方法
如果您要清理旧代码,可以编写一个导出所需变量的模块.每当您觉得需要调用create_glob_var时,请将该变量添加到此包并将其放入导入列表中.
这将帮助您跟踪正在发生的事情以及变量的使用方式.
package MyVars; use strict; use warnings; use Exporter 'import'; our($x,%y,@z); our @EXPORT_OK = qw( $x %y @z );
剧本:
#!/usr/bin/perl use strict;use warnings; use MyVars qw( $x %y @z ); $x = 'test'; %y = (a => 1,b => 2); @z = qw( a b c); use Data::Dumper; print Dumper \($x,@z);
输出:
$VAR1 = \'test';
$VAR2 = {
'a' => 1,'b' => 2
};
$VAR3 = [
'a','b','c'
];