简体   繁体   English

如何替换 Perl 哈希键?

[英]How can I replace a Perl hash key?

Let us say if I have a hash like this:假设我有这样的哈希:

$data = {
    'key1' => {
                'key2' => 'value1'
              },
    'key3' => {
                'key4' => {
                            'key5' => 'value2'
                          }
              },
};

Now, how can I replace the the key 'key5' with some other key name, say 'key6'?现在,我如何用其他键名替换键“key5”,比如“key6”?

I know how to loop through the hash and dump the values, but I don't know how to replace keys or values in place.我知道如何遍历散列并转储值,但我不知道如何替换键或值到位。

The delete operator returns the value being deleted. delete运算符返回被删除的值。 So this所以这

$data->{key3}{key4}{key6} = delete $data->{key3}{key4}{key5}

will do what you're looking for.会做你正在寻找的。

You can't replace it, but you can make a new key easily, and then delete() the old one:您无法替换它,但您可以轻松创建一个新密钥,然后delete()旧密钥:

$data->{key3}{key4}{key6} = $data->{key3}{key4}{key5};
delete $data->{key3}{key4}{key5};

Of course, you could make a fairly simple subroutine to do this.当然,您可以制作一个相当简单的子程序来执行此操作。 However, my first approach was wrong, and you would need to make a more complex approach that passes in the data structure to modify and the element to be modified, and given that you want elements several levels deep this may be difficult.但是,我的第一种方法是错误的,您需要采用更复杂的方法,传入要修改的数据结构和要修改的元素,并且考虑到您希望元素深入多个级别,这可能很困难。 Though if you don't mind a little clutter:虽然如果你不介意有点混乱:

sub hash_replace (\%$$) {
  $_[0]->{$_[2]} = delete $_[0]->{$_[1]}; # thanks mobrule!
}

Then call it:然后调用它:

hash_replace %{$data->{key3}{key4}}, "key5", "key6";

Or the cool way (How better to say that we're transforming "key5" into "key6" ?):或者很酷的方式(最好说我们正在将“key5”转换为“key6”?):

hash_replace %{$data->{key3}{key4}}, key5 => "key6";

(Tested and works) (经过测试并有效)

This 'works', but it is very hard-coded.这“有效”,但它是非常硬编码的。

#!/bin/perl -w
use strict;

my $data = {
    'key1' => {
        'key2' => 'value1'
    },
    'key3' => {
        'key4' => {
            'key5' => 'value2'
        }
    },
};

print "$data->{key3}->{key4}->{key5}\n";

my $save = $data->{key3}->{key4}->{key5};
delete $data->{key3}->{key4}->{key5};
$data->{key3}->{key4}->{key6} = $save;

print "$data->{key3}->{key4}->{key6}\n";

You can eliminate the '->' operators between the hash subscripts, but not the one after '$data' - as in Chris Lutz's solution .您可以消除散列下标之间的 '->' 运算符,但不能消除 '$data' 之后的运算符 - 如Chris Lutz 的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM