【问题标题】:Error when accessing array of hashes访问哈希数组时出错
【发布时间】:2017-10-04 19:52:45
【问题描述】:

我正在尝试生成一个哈希列表,并使用以下脚本与用户交互:

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.

【问题讨论】:

    标签: arrays perl hash hash-reference


    【解决方案1】:

    在 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]};
    

    类似消息

    哈希(0x2587a88)

    来自这一行:

    打印“@hashes\n”;

    不确定您的意图是什么,但是如果您想查看内容,则需要遍历数据结构(它将是对哈希的引用数组)。您可以考虑使用 Data::Dumper 模块来帮助您查看那里的内容。

    【讨论】:

    • my @foo = (); my %bar = (); 是多余的。你可以直接写my @foo; my %bar;
    • 非常感谢,现在可以使用了。没有意识到我正在用大括号初始化一个引用。我现在看得更清楚了 :) 并感谢您建议使用 Dumper。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-22
    • 2015-04-28
    • 2012-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-06
    相关资源
    最近更新 更多