arraysperldictionaryhashhashref

Perl - Create Array of Hashes based on Hash filter


I have this hash that contains some information:

my %hash = (
    key_1 => {
        year => 2000,
        month => 02,
    }, 
    key_2 => {
        year => 2000,
        month => 02,
    }, 
    key_3 => {
        year => 2000,
        month => 03,
    }, 
    key_4 => {
        year => 2000,
        month => 05,
    }, 
    key_5 => {
        year => 2000,
        month => 01,
    }
);

I wan't to create an array of hashes in which each of the array elements, lists every single hash key/value pairs that has the same year and month.

So basically I want to create something like this:

$VAR1 = [
    'key_1' => {
        'month' => 2,
        'year' => 2000
    },
    'key_2' => {
        'month' => 2,
        'year' => 2000
    }
], [
    'key_3' => {
        'month' => 3,
        'year' => 2000
    }
], [
    'key_4' => {
        'month' => 3,
        'year' => 2000
    }
], [
    'key_5' => {
        'year' => 2000,
        'month' => 1
    }
];

The real question here is: How can I compare a hash key key value's to other key key value's and make a map out of it.

Thank you for your time! =)


Solution

  • I'm getting a slightly different results - key_3 and key_4 should belong to the same group.

    my %by_year_and_month;
    undef $by_year_and_month{ $hash{$_}{year} }{ $hash{$_}{month} }{$_}
        for keys %hash;
    
    my $result;
    for my $year (keys %by_year_and_month) {
        for my $month (keys %{ $by_year_and_month{$year} }) {
            push @$result, [ map { $_ => { month => $month, year => $year } }
                             keys %{ $by_year_and_month{$year}{$month} } ];
        }
    }