2017-05-06 65 views
1

我试图生成散列的列表,使用下面的脚本与用户交互的数组时:错误访问哈希

use strict; 
use warnings; 

my $KEY_1 = "one"; 
my $KEY_2 = "two"; 


sub generateHash{ 
    my ($value1, $value2) = (@_); 

    $value2 = $value1 + 5.0; 

    my %hash = {}; 

    $hash{$KEY_1} = $value1; 
    $hash{$KEY_2} = $value2; 

    return %hash; 
} 

print "Num: \n"; 
my $number = <>; 

my @hashes =(); 
my %new_hash = {}; 

for (my $i = 1; $i < $number + 1; $i = $i + 1) { 

    print "Enter the values $i \n"; 

    print "value 1: "; 
    my $value1= <>; 

    print "\nvalue 2: "; 
    my $value2= <>; 

    chomp $value1; 
    chomp $value2; 

    %new_hash = generateHash($value1, $value2);  

    push (@hashes, %new_hash); 
    print "@hashes\n"; 
} 

my %test = $hashes[0]; 
my @keys = keys %test; 
my @values = values %test; 

print "@keys\n"; 
print "@values\n"; 

当我尝试执行程序,它提出了一些相关的错误访问数组中的哈希时使用引用。我错过了一些东西,但我看不到是什么,我想知道我在哪里访问哈希引用。谢谢你在前进,连接从运行的输出:

Num: 
1 
Reference found where even-sized list expected at generate_hashes.pl line 21, <> line 1. 
Enter the values 1 
value 1: 1 

value 2: 1 
Reference found where even-sized list expected at generate_hashes.pl line 12, <> line 3. 
Use of uninitialized value $hashes[1] in join or string at generate_hashes.pl line 32, <> line 3. 
HASH(0x2587a88) one 1 two 6 
Odd number of elements in hash assignment at generate_hashes.pl line 34, <> line 3. 
HASH(0x2587a88) 
Use of uninitialized value $values[0] in join or string at generate_hashes.pl line 38, <> line 3. 

回答

2

参考找到预期在generate_hashes.pl线甚至大小列表21,<> 1号线

这一个是由于到

my %new_hash = {}; 

空的大括号{}提供一个空的散列的引用,但在左手边你有一个哈希,而不是一个参考。您可以改为使用初始化:

my %new_hash =(); 

但(作为注释)你不知道在实践中需要初始化,如果你想开始一个空的哈希值;这是默认设置。

参考发现,甚至大小列表预期在generate_hashes.pl线12,<>线3

相同的故障与上述generateHash函数内。

在这一行:

push (@hashes, %new_hash); 

我怀疑你打算到哈希参考推入阵,要做到这一点,你需要添加一个\

push(@hashes, \%new_hash); 

否则你”将整个数据结构放在阵列中等。

在这一行:

my %test = $hashes[0]; 

你的右手边是一个标量,一个散列的引用,因此,您需要解引用,以使用散列分配:

my %test = %{$hashes[0]}; 

消息像

HASH(0x2587a88)

从这一行来:

打印 “@hashes \ n”;

不确定你的意图是否存在,但是如果你想查看内容(它将是一个哈希引用数组),你需要迭代数据结构。您可以考虑使用Data :: Dumper模块来帮助您查看其中的内容。

+1

'my @foo =();我的%bar =();'是多余的。你可以写'我的@foo;我的%吧;'而是。 – melpomene

+0

非常感谢,它现在有效。没有意识到我正在用大括号初始化参考。我现在看到的事情更清晰:)并感谢提议使用Dumper。 – Hellzzar