Search code examples
perlhashperl-data-structures

Creating hash by Key-Value pairing from a list


Following is the code:

#!/usr/bin/perl

my %hash = (1..20);

foreach (sort {$a <=> $b} keys %hash)
{
  print "\n$_ -> $hash{$_} ";
}

Output:

1 -> 2 
3 -> 4 
5 -> 6 
7 -> 8 
9 -> 10 
11 -> 12 
13 -> 14 
15 -> 16 
17 -> 18 
19 -> 20 

Perl picks up first element as key and the next element as value. That is, alternate values of the list are taken as keys. And the value in between as its value.

Is it possible to control this assignment?

Like-

I have a list (1..20) Is it possible to assign next two elements as values to key?

I need to modify my %hash = (1..20) to achieve same.

1 -> (2,3) 
4 -> (5,6)
7 -> (8,9)
10 -> (11,12)
13 -> (14,15)

etc...


Solution

  • use List::MoreUtils 'natatime';
    
    my $it = natatime 3, (1 .. 20);
    my %hash;
    while (my ($k, @vals) = $it->()) {
      $hash{$k} = \@vals;
    }
    
    use Data::Dump;
    dd \%hash;
    

    output

    {
      1  => [2, 3],
      4  => [5, 6],
      7  => [8, 9],
      10 => [11, 12],
      13 => [14, 15],
      16 => [17, 18],
      19 => [20],
    }