简体   繁体   English

复制数组的哈希值的前N个键和值

[英]Copying the first N keys and values of a Hash of array

I have a hash of arrays. 我有一个数组的哈希。

%HoA = (
    'C1' =>  ['1', '3', '3', '3'],
    'C2' => ['3','2'],
    'C3' => ['1','3','3','4','5','5'],
    'C4'  => ['3','3','4'],
    'C5' => ['1'],
);

I would like to write a subroutine that returns a "sub copy" hash of arrays that contains the first N keys (and their values) of the original hash of arrays. 我想编写一个子例程,该例程返回数组的“子副本”散列,其中包含原始数组散列的前N个键(及其值)。

Something like this 像这样

my %HoA2 = new_partition(\%HoA, 3);

And it returns a new HoA data structure: 它返回一个新的HoA数据结构:

%HoA = (
    'C1' =>  ['1', '3', '3', '3'],
    'C2' => ['3','2'],
    'C3' => ['1','3','3','4','5','5'],
 );

Is there a way to do this by scratch without using a module? 有没有办法在不使用模块的情况下从头开始?

There are no "first N elements", as the order of hash keys is not defined and thus, cannot be relied upon. 由于没有定义哈希键的顺序,因此不能依靠它,因此没有“前N个元素”。

If you want any three elements instead of first three, you could use 如果要使用任何三个元素而不是前三个,则可以使用

%HoA = @HoA{ ( keys %HoA )[0..2] };

As has been correctly stated, the order of elements in a hash is undefined. 正如已经正确说明的那样,哈希中元素的顺序是不确定的。 But if you can impose your own order on the elements, then it is simple enough to extract the elements that you require: 但是,如果您可以将自己的顺序强加于元素,那么提取所需元素就足够简单了:

my %HoA = (
    'C1' => ['1', '3', '3', '3'],
    'C2' => ['3','2'],
    'C3' => ['1','3','3','4','5','5'],
    'C4' => ['3','3','4'],
    'C5' => ['1'],
);

# Use an array slice to grab the first 3 keys from a sorted list of %HoA keys.
# Use map to create a new hash that contains the keys and the values from the
# original hash:
my %HoA2 = map { $_ => $HoA{$_} } (sort keys %HoA)[0..2];

# Alternatively, specify the exact keys that you require:
my %HoA3 = map { $_ => $HoA{$_} } qw(C1 C2 C3);

# { C1 => [1, 3, 3, 3], C2 => [3, 2], C3 => [1, 3, 3, 4, 5, 5] }

Update 更新资料

As Borodin points out, the above method copies references, so changes to one hash will be reflected in the other: 正如Borodin所指出的,上述方法复制了引用,因此对一个哈希的更改将反映在另一个哈希中:

push @{$HoA{C1}}, 9;

# %HoA2 and %HoA3:
# { C1 => [1, 3, 3, 3, 9], C2 => [3, 2], C3 => [1, 3, 3, 4, 5, 5] }

To prevent that, copy the array itself: 为防止这种情况,请复制数组本身:

my %HoA4 = map { $_ => [@{ $HoA{$_} }] } qw(C1 C2 C3);

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

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