Home > Enterprise >  Perl - transforming one data structure into another
Perl - transforming one data structure into another

Time:07-08

I'm trying to convert one data structure into another, using Perl.

my $agent_details = $dbh->selectall_arrayref(
    "SELECT agent_id, year, type FROM agents ORDER BY agent_id",
    { Slice => {} }
);

I end up with the data structure:

$VAR1 = [
          {
            'agent_id' => '1',
            'year' => '2000',
            'type' => '14',
          },
          {
            'agent_id' => '2',
            'year' => '2001',
            'type' => '14',
          },
          {
            'agent_id' => '3',
            'year' => '2002',
            'type' => '14',
          },
          {
            'agent_id' => '4',
            'year' => '2000',
            'type' => '14',
          },
          {
            'agent_id' => '5',
            'year' => '2001',
            'type' => '14',
          },
          {
            'agent_id' => '6',
            'year' => '2002',
            'type' => '14',
          },
]

What I would like to do is transform into a hash of arrays:

$VAR2 = {
          '2000' => [1, 4],
          '2001' => [2, 5],
          '2002' => [3, 6],
}

I was able to accomplish this with some ugly loops, but I feel like there is an easier / better cleaner way to do it.

CodePudding user response:

my %agents_by_year;
for $agent ( @$agents ) {
   push @{ $agents_by_year{ $agent->{ year } } }, $agent->{ agent_id };
}
  • Related