在Perl中更改多维哈希的第一个键 [英] Change first key of multi-dimensional Hash in perl

查看:152
本文介绍了在Perl中更改多维哈希的第一个键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在perl中有一个多维哈希,我想更改所选值的第一个键.例如,我有哈希

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;

现在,我想将第一个键中的值3替换为值300.之后,我将得到:

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;
        }
    }
}

但是有更快的方法吗?

推荐答案

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

这篇关于在Perl中更改多维哈希的第一个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆