Search code examples
arraysperlhashsubroutine

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.

Something like this

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

And it returns a new HoA data structure:

%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?


Solution

  • There are no "first N elements", as the order of hash keys is not defined and thus, cannot be relied upon.

    If you want any three elements instead of first three, you could use

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