gpt4 book ai didi

perl - 如何从 Perl 数组中获取哈希值?

转载 作者:行者123 更新时间:2023-12-01 22:48:52 25 4
gpt4 key购买 nike

这是代码:

my @items = (); # this is the array
my %x = {}; # the hash I'm going to put into the array
$x{'aa'} = 'bb'; # fill it up with one key-value pair
push(@items, $x); # add it to the array
my %i = @items[0]; # taking it back
print $i{'aa'}; # taking the value by the key

我希望它打印bb,但它没有打印任何东西。我做错了什么?

最佳答案

What am I doing wrong?

好吧,这和你想的不一样:

my %x = {};

您可以轻松检查:

use Data::Dumper;
print Dumper \%x;

输出:

Reference found where even-sized list expected at ./1.pl line 5.
$VAR1 = {
'HASH(0x556a69fe8220)' => undef
};

第一行来自use warnings;。如果您不使用它,请立即开始。

为什么hash的内容这么奇怪?大括号创建一个散列引用。由于键必须是字符串,引用被字符串化为 HASH(0xADDR)。您不需要引用,您需要键和值列表。

my %x = ();

事实上,每个散列和数组开始时都是空的,因此您不必使用任何东西:

my @items;
my %x;

或者,您可以直接填充它,而不是在下一行单独填充:

my %x = (aa => 'bb');

同样,这不起作用:

push @items, $x;

它将标量变量$x 的值压入@items,但没有这样的变量。您似乎没有使用 use strict;。现在就开始吧,它将避免您犯类似的错误。

您想将散列推送到数组,但数组值是标量 - 因此您需要取而代之的是散列的引用。

push @items, \%x;

不,您想从数组中检索散列。同样,这不起作用:

my %i = @items[0];

您正在提取单个值。因此,您不应使用 @。此外,我们现在在数组中有一个引用,要填充哈希,我们需要先取消引用它:

my %i = %{ $items[0] };

瞧,它起作用了!

#!/usr/bin/perl
use warnings;
use strict;

my @items; # this is the array
my %x; # the hash I'm going to put into the array
$x{aa} = 'bb'; # fill it up with one key-value pair
push @items, \%x; # add it to the array
my %i = %{ $items[0] }; # taking it back
print $i{aa}; # taking the value by the key

关于perl - 如何从 Perl 数组中获取哈希值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74761216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com