我想更改存储在哈希中的变量,但我一直收到错误消息:
"Can't use the string ("SCALAR(0x30f558)") as a SCALAR ref while "strict refs" in use at - line 14.
我的简化代码如下:
#!/usr/bin/perl
use strict;
use warnings;
my $num = 1234;
my $a = 5;
my %hash = (\$num => "value");
foreach my $key (keys %{hash}){
print "Key: $key\n";
#OPTION1: $a = $$key;
}
my $ref = \$num ;
print "Ref: $ref\n";
#OPTION2: $a = $$ref ;
print $a;
运行此打印:
Key: SCALAR(0x30f558)
Ref: SCALAR(0x30f558)
5
表明 $key 和 $ref 都指向同一个变量 - $num
此外,如果 $key 和 $ref 相同,则 OPTION1 和 OPTION2 上的代码相同。
当我取消注释 OPTION2 时,$a 打印为 1234。
但是,当我取消注释 OPTION1 时,我收到上面显示的错误。
问题:如何使用我在 OPTION1 中尝试做的哈希将 $a 更改为 $num?为什么这不能按原样工作?
参考资料:
http
://cpansearch.perl.org/src/CHIPS/perl5.004_05/t/pragma/strict-refs
我密切关注这段代码:
use strict 'refs' ;
my $fred ;
my $b = \$fred ;
my $a = $$b ;
在我引入哈希之前,它没有造成任何错误。
谢谢您的帮助。
原始代码(不起作用):
#User Defined - here are the defaults
my $a = 122160;
my $b = 122351;
my $c = 'string';
my $d = 15;
my $e = 123528;
#etc.
#Create variable/print statement hash
my %UserVariables = (
\$a => "A: (Default: $a): ",
\$b => "B: (Default: $b): ",
\$c => "C: (Default: $c): ",
\$d => "D: (Default: $d): ",
\$e => "E: (Default: $e): ",
);
#Allow user to change variables if desired
foreach (keys %UserVariables){
print $UserVariables{$_};
chomp (my $temp = <>);
print "$_\n";
$$_ = $temp unless ($temp eq '');
print "$temp\n" unless ($temp eq '');
};
效率较低但有效的方法:
#Alternate Method without loops (not ideal)
my $temp;
print $UserVariables{\$a};
chomp ($temp = (<>));
$a= $temp unless ($temp eq '');
print $UserVariables{\$b};
chomp ($temp = (<>));
$b= $temp unless ($temp eq '');
print $UserVariables{\$c};
chomp ($temp = (<>));
$c= $temp unless ($temp eq '');
print $UserVariables{\$d};
chomp ($temp = (<>));
$d= $temp unless ($temp eq '');
print $UserVariables{\$e};
chomp ($temp = (<>));
$e= $temp unless ($temp eq '');