我試圖生成散列的列表,使用下面的腳本與用戶交互的數組時:錯誤訪問哈希
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.
'my @foo =();我的%bar =();'是多餘的。你可以寫'我的@foo;我的%吧;'而是。 – melpomene
非常感謝,它現在有效。沒有意識到我正在用大括號初始化參考。我現在看到的事情更清晰:)並感謝提議使用Dumper。 – Hellzzar