perl-将一个数据结构转换为另一个数据结构

发布于 2025-02-13 14:07:23 字数 1202 浏览 0 评论 0原文

我正在尝试使用Perl将一个数据结构转换为另一种数据结构。

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

我最终以数据结构的方式:

$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',
          },
]

我想做的就是变成阵列的哈希:

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

我能够用一些丑陋的循环来完成此操作,但是我觉得有一种更容易 /更好的清洁方法可以做到这一点。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

抱着落日 2025-02-20 14:07:23
my %agents_by_year;
for $agent ( @$agents ) {
   push @{ $agents_by_year{ $agent->{ year } } }, $agent->{ agent_id };
}
my %agents_by_year;
for $agent ( @$agents ) {
   push @{ $agents_by_year{ $agent->{ year } } }, $agent->{ agent_id };
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文