Hash / Foreach中的Perl变量引用

时间:2012-07-26 18:50:42

标签: perl reference

我想更改存储在哈希中的变量,但我一直收到错误:
"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 '');

2 个答案:

答案 0 :(得分:3)

Perl哈希键只能是字符串。您没有引用作为键,但您的引用自动字符串化为:逐字字符串“SCALAR(0x30f558)”。显然,字符串不能作为参考。

您应该重新考虑存储数据的方式,并且可以在更多细节上解释 ,而不是关注如何

在您举例说明的特定情况下,只需对要覆盖的值使用纯哈希:

my %config = (
   a => 122160,
   b => 122351,
   c => 'string',
   d => 15,
   e => 123528,
);

...然后覆盖此哈希中的值。

答案 1 :(得分:1)

我想更改存储在哈希
中的变量

就像你不能在变量中存储变量一样,你不能将变量存储在哈希中。您可以在哈希中存储值(包括对变量的引用)。 (例如代码中的字符串value。)

显示$ key和$ ref都指向同一个变量 - $ num

没有。它表明$key$ref的值具有相同的字符串化。

但是,当我取消注释OPTION1时,我收到上面显示的错误。

哈希表键必须是字符串,就像数组键必须是非负整数一样。

我密切关注这段代码:

不,哈希的情况也一样。

use strict 'refs' ;
my %hash = ( fred => undef );
my $b = \$hash{fred} ;
my $a = $$b ;

我无法提供解决方案,因为您没有说出您要做的事情。