Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/apache-flex/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
解码哈希::perl中的多值就地_Perl - Fatal编程技术网

解码哈希::perl中的多值就地

解码哈希::perl中的多值就地,perl,Perl,有物体的。键和值可以是utf8编码的字节字符串。需要就地解码 以下是我想要的: 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(s

有物体的。
可以是utf8编码的字节字符串。需要就地解码

以下是我想要的:

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á

但是sub
decodehm
-并不“好”。有可能以更“优雅”的形式解决问题吗?

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