在perl中解码Hash :: MultiValue inplace

时间:2015-10-18 18:17:00

标签: perl

拥有Hash::MultiValue个对象。 keysvalues可以是utf8编码的字节串。需要解码它们 inplace

以下是我想要的:

use 5.014;
use warnings;
use Hash::MultiValue;
use Encode;

my $hm = make_demo_data(); # the $hm is Hash::MultiValue
                           # the keys and values are utf8 encoded byte-strings
$hm->each(sub { print "$_[0]: $_[1]\n" });

decodehm($hm); #decode the $hm inplace

say "--decoded--";    
binmode(STDOUT, ':utf8');
$hm->each(sub { print "$_[0]: $_[1]\n" });

sub decodehm {
    my $hm = shift;
    #make copy - but decoded
    my $new = Hash::MultiValue->new( map Encode::decode_utf8($_), $hm->flatten );
    $hm->clear; #clear the original
    $new->each( sub { $hm->add($_[0], $_[1]) });    #set each element in the original $hm
}

sub make_demo_data { #utf8 encoded byte-strings
    return Hash::MultiValue->new(
        "k1\x{c3}\x{a1}" => "v1a\x{c3}\x{a1}",
        "k1\x{c3}\x{a1}" => "v1b\x{c3}\x{a1}",
        "k2a" => "v2aa",
        "k3\x{c3}\x{a1}" => "v3a\x{c3}\x{a1}",
    );
}

例如。在utf8终端上打印想要的结果

k1á: v1aá
k1á: v1bá
k2a: v2aa
k3á: v3aá
--decoded--
k1á: v1aá
k1á: v1bá
k2a: v2aa
k3á: v3aá

但是子decodehm - 不是"很好"。有可能解决问题更多"优雅"形成的?

1 个答案:

答案 0 :(得分:2)

听起来你问是否可以更改密钥(即解码密钥)而不删除原始元素并重新插入。如果是这样,答案是否定的。对于散列,数学函数(散列函数)将键转换为索引。更改密钥可以更改索引,因此更改密钥需要将值从旧索引移动到新索引,因此更改密钥需要删除并重新插入值。