Ros*_*ers 7 perl symbolic-references
在Perl中,是否可以基于字符串创建全局变量?
例如,如果我有一个像这样的功能:
sub create_glob_var {
my ($glob_var_str) = @_;
# something like this ( but not a hash access).
our ${$glob_var_str};
};
Run Code Online (Sandbox Code Playgroud)
我称之为:
create_glob_var( "bar" );
Run Code Online (Sandbox Code Playgroud)
我如何修改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";
Run Code Online (Sandbox Code Playgroud)
生产:
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.
注意我意识到使用全局变量会导致臭氧消耗和男性型秃发.我正在尝试清理一些已经完全被全局变量感染的遗留代码.一次一个重构......
如果要尝试清理旧代码,可以编写一个导出所需变量的模块.每当您觉得需要调用时create_glob_var,请将此变量添加到此包并将其放入导入列表中.
这将帮助您跟踪正在发生的事情以及变量的使用方式.
package MyVars;
use strict; use warnings;
use Exporter 'import';
our($x, %y, @z);
our @EXPORT_OK = qw( $x %y @z );
Run Code Online (Sandbox Code Playgroud)
剧本:
#!/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, %y, @z);
Run Code Online (Sandbox Code Playgroud)
输出:
$VAR1 = \'test';
$VAR2 = {
'a' => 1,
'b' => 2
};
$VAR3 = [
'a',
'b',
'c'
];