如何将重复键的值添加到键中:[值数组]在Perl中

时间:2018-03-09 20:14:46

标签: perl hash collision

我正在尝试在哈希值中向数组添加值以避免冲突。

想象一下读取键值对:

my %color_of = (
    apple  => "red",
    orange => "orange",
    apple  => "green",
);

如何将apple的值附加到像这样的值数组?

my %color_of = (
    apple  => ["red", "green"],
    orange => "orange",
);

编辑:正如所建议的那样,为碰撞创建更好的数据结构是:

my %color_of = (
    apple  => ["red", "green"],
    orange => ["orange"],
);    

这允许将所有值推送到键的数组中。

2 个答案:

答案 0 :(得分:2)

my @pairs=(
    apple  => "red",
    orange => "orange",
    apple  => "green",
);
my %color_of;
push @{ $color_of{shift@pairs} }, shift@pairs while @pairs;
@$_==1 and $_=$$_[0] for values %color_of; #one elem arrays becomes scalar

use Data::Dumper; print Dumper(\%color_of);

如果你不想破坏@pairs

my %color_of = sub{ my %h; push@{ $h{shift()} }, shift while@_; %h }->(@pairs);

答案 1 :(得分:0)

当考虑从SQL查询中返回值时,如下所示:

[[apple, "red"], [orange, "orange"], [apple, "green"]]

我能够找到解决这个问题的好方法,比我帖子上的评论解决方案容易得多。

my %hash;
foreach my $res (@rs)
{
        push @{$hash{$res->[0]}}, $res->[1];
}