Change first key of multi-dimensional Hash in perl

我的梦境 提交于 2020-07-21 03:09:10

问题


I have a multi-dimensional hash in perl and I would like to change the first key for a chosen value. For example, I have the hash

my %Hash1;
$Hash1{1}{12}=1;
$Hash1{1}{10}=1;
$Hash1{2}{31}=1;
$Hash1{3}{52}=1;
$Hash1{3}{58}=1;
$Hash1{4}{82}=1;
$Hash1{4}{154}=1;

Now I want to replace the value 3 in the first key with the value 300. After this I would get:

$Hash1{1}{12}=1;
$Hash1{1}{10}=1;
$Hash1{2}{31}=1;
$Hash1{300}{52}=1;
$Hash1{300}{58}=1;
$Hash1{4}{82}=1;
$Hash1{4}{154}=1;

I know I could create a new hash by scanning the original hash and doing the following:

my %Hash2;
foreach my $key1 (sort keys %Hash1) {
    foreach my $key2 (keys %{ $Hash1{$key1} }) {
        if($key1==3){
            $Hash2{300}{$key2}=1;
        } else {
            $Hash2{$key1}{$key2}=1;
        }
    }
}

But is there a quicker way?


回答1:


$Hash1{300} = $Hash1{3};
delete $Hash1{3};


来源:https://stackoverflow.com/questions/62596637/change-first-key-of-multi-dimensional-hash-in-perl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!