gpt4 book ai didi

perl - perl中散列的散列问题

转载 作者:行者123 更新时间:2023-12-05 09:00:06 25 4
gpt4 key购买 nike

我在访问哈希的哈希中的变量时遇到问题我不知道我做错了什么。在调试 hash %list1 的值时给出一个 undef,所以我无法得到我的值。

use strict ;
use warnings ;
my $text = "The, big, fat, little, bastards";
my $Author = "Alex , Shuman ,Directory";
my %hashes = {1,2,3,40};
my %count = ();
my @lst = split(",",$text);
my $i = 0 ;
my @Authors = split(",", $Author);
foreach my $SingleAuthor(@Authors)
{
foreach my $dig (@lst)
{

$count{$SingleAuthor}{$dig}++;
}
}

counter(\%count);

sub counter
{
my $ref = shift;
my @SingleAuthors = keys %$ref;
my %list1;
foreach my $SingleAuthor1(@SingleAuthors)
{
%list1 = $ref->{$SingleAuthor1};
foreach my $dig1 (keys %list1)
{

print $ref->{$SingleAuthor1}->{$dig1};
}
}


}

最佳答案

在两个地方,您试图将散列引用分配给散列,这会导致出现此警告:在需要偶数大小列表的地方找到了引用

这里有两个你需要的编辑:

# I changed {} to ().
# However, you never use %hashes, so I'm not sure why it's here at all.
my %hashes = (1,2,3,40);

# I added %{} around the right-hand side.
%list1 = %{$ref->{$SingleAuthor1}};

参见 perlreftut用于对复杂数据结构进行有用且简短的讨论。

就其值(value)而言,您的 counter() 方法可以通过删除中间变量而在不损失可读性的情况下得到简化。

sub counter {
my $tallies = shift;
foreach my $author (keys %$tallies) {
foreach my $dig (keys %{$tallies->{$author}}) {
print $tallies->{$author}{$dig}, "\n";
}
}
}

或者,正如 ysth 指出的那样,如果您不需要 key ,则像这样:

    foreach my $author_digs (values %$tallies) {   
print $dig, "\n" for values %$author_digs;
}

关于perl - perl中散列的散列问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6557452/

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