在 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";
产生:
变量“$bah”未在 /nfs/pdx/home/rbroger1/tmp2.pl 第 12 行导入。 全局符号“$bah”在 /nfs/pdx/home/rbroger1/tmp2.pl 第 12 行需要明确的包名称。 /nfs/pdx/home/rbroger1/tmp2.pl 的执行由于编译错误而中止。
注意我意识到使用全局变量会导致臭氧消耗和男性型秃发。我正在尝试清理一些已经完全感染了使用全局变量的遗留代码。一次重构一个...