用Perl求和哈希元素

时间:2012-11-22 10:13:30

标签: perl hash sum

我有一个返回此哈希结构的Perl脚本:

$VAR1 = {
          'Week' => [
                      '1238',
                      {
                        'OUT3FA_5' => 65,
                        'OUT3A_5' => 20,
                        'OUT3-Fix' => 45,
                        'IN1' => 85
                      },
                      '1226',
                      {
                        'OUT3FA_5' => 30,
                        'OUT3A_5' => 5,
                        'OUT3-Fix' => 25,
                        'IN1' => 40
                      }
                    ]
        };

我想要做的是,计算每周IN1的总数,在这种情况下,它会返回:

$VAR1 = {
          'Week' => [
                      '1238',
                      {
                        'OUT3FA_5' => 65,
                        'Total_IN1' => 85,
                        'OUT3A_5' => 20,
                        'OUT3-Fix' => 45,
                        'IN1' => 85
                      },
                      '1226',
                      {
                        'OUT3FA_5' => 30,
                        'Total_IN1' => 125,
                        'OUT3A_5' => 5,
                        'OUT3-Fix' => 25,
                        'IN1' => 40
                      }
                    ]
        };

每周等等。

我该怎么办?任何帮助将不胜感激。

这是我试图做的但是它不起作用:

my @sum_IN1 = qw(IN1); #kinda useless to use an array just for one value...
for my $num (keys %hash) {

    my $found;
    my $sum = 0;

    for my $key (@sum_IN1) {

        next unless exists $hash{$num}{$key};
        $sum   += $hash{$num}{$key};
        $found = 1;
    }

    $hash{$num}{Total_IN1} = $sum if $found;
} 

4 个答案:

答案 0 :(得分:2)

首先,您的数据结构令人困惑。 'Week'是对数组的引用,其中一些元素是字符串(例如'1238'),其余元素是哈希引用。

虽然Perl可以让你侥幸成功,但对于每个级别的数据结构来说,只有一种东西才能更好。这是需要考虑的事情。但是,我现在将其保留原样。

这是一种快速的方法:

my $ttl = 0;
$_->{'In1Total'} = $ttl+=$_->{'IN1'} || 0 for(grep {ref $_} @{$VAR1->{'Week'}});

use Data::Dumper;
print Dumper $VAR1;

更新:已将//更改为||,正如Mikko L建议的那样。

说明:

grep {ref $_}只获取数组中散列引用的元素。

$_->{'IN1'} || 0 - 如果其中一个哈希没有'IN1',则会使用零代替。这基本上是对正在定义的散列键的检查。对于哈希键,||可以接受此操作。但是,在其他情况下,您需要使用定义的或运算符(//,我相信版本为5.10)。

$_->{'In1Total'} = $total+=$_->{'IN1'} || 0这会将IN1的当前值添加到计数中,然后将结果放入In1Total。不可否认,通过将其分成几行可以使这一点更加清晰。

更新2:修正了错误Borodin指出。

答案 1 :(得分:2)

您需要保留一个状态变量,其中包含数组中每个项目的运行总计。我还怀疑你Week数组应该是一个哈希?

use strict;
use warnings;

use Data::Dump;

my $data = {
  Week => [
    1238,
    { "IN1" => 85, "OUT3-Fix" => 45, "OUT3A_5" => 20, "OUT3FA_5" => 65 },
    1226,
    { "IN1" => 40, "OUT3-Fix" => 25, "OUT3A_5" => 5, "OUT3FA_5" => 30 },
  ],
};

my $week = $data->{Week};

# Sort the array entry pairs by week number
#
my @pairs;
push @pairs, [ splice @$week, 0, 2 ] while @$week;
@$week = ();
for my $pair (sort { $a->[0] <=> $b->[0] } @pairs) {
  push @$week, @$pair;
}

# Calculate the running totals of IN1
#
my $total = 0;
for my $item (@$week) {
  next unless ref $item eq 'HASH' and exists $item->{IN1};
  $total += $item->{IN1};
  $item->{Total_IN1} = $total;
}

dd $data;

<强>输出

{
  Week => [
    1226,
    {
      "IN1"       => 40,
      "OUT3-Fix"  => 25,
      "OUT3A_5"   => 5,
      "OUT3FA_5"  => 30,
      "Total_IN1" => 40,
    },
    1238,
    {
      "IN1"       => 85,
      "OUT3-Fix"  => 45,
      "OUT3A_5"   => 20,
      "OUT3FA_5"  => 65,
      "Total_IN1" => 125,
    },
  ],
}

答案 2 :(得分:0)

在没有看到你的代码的情况下,很难看出它为什么不起作用,但可能是因为你在代码中使用了一个哈希,但返回的数据结构是一个哈希引用。

这是一个应该工作的版本(使用哈希引用):

#!/usr/bin/env perl

use warnings;
use strict;
use Data::Dumper;
use List::MoreUtils qw( natatime );

my $data = {
    'Week' => [
        '1238',
        {   'IN1'      => 85,
            'OUT3FA_5' => 65,
            'OUT3A_5'  => 20,
            'OUT3-Fix' => 45
        },
        '1226',
        {   'IN1'      => 40,
            'OUT3FA_5' => 30,
            'OUT3A_5'  => 5,
            'OUT3-Fix' => 25
        }
    ]
};

for my $key ( keys %$data ) {
    my $weekly_data = $data->{$key};
    my $total       = 0;
    my $iter        = natatime 2, @$weekly_data;

    while ( my ( $id, $daily_data ) = $iter->() ) {
        next unless $daily_data->{IN1};
        $total += $daily_data->{IN1};
        $daily_data->{Total_IN1} = $total;
    }
}

print Dumper($data);
1;

这是输出:

$VAR1 = {
          'Week' => [
                      '1238',
                      {
                        'OUT3FA_5' => 65,
                        'Total_IN1' => 85,
                        'OUT3A_5' => 20,
                        'OUT3-Fix' => 45,
                        'IN1' => 85
                      },
                      '1226',
                      {
                        'OUT3FA_5' => 30,
                        'Total_IN1' => 125,
                        'OUT3A_5' => 5,
                        'OUT3-Fix' => 25,
                        'IN1' => 40
                      }
                    ]
        };

答案 3 :(得分:0)

也许你可以通过修改你的代码来学到一些东西,顺便说一句,它完美无缺。问题是你对数据结构的处理是错误的。这样:

# initial data structure
my $data = {
    'Week' => [
        '1238',
        {
            'IN1' => 85,
            'OUT3FA_5' => 65,
            'OUT3A_5' => 20,
            'OUT3-Fix' => 45
        },
        '1226',
        {                        
            'IN1' => 40,
            'OUT3FA_5' => 30,                       
            'OUT3A_5' => 5,
            'OUT3-Fix' => 25
        },
    ],
};

是哈希引用。在引用的哈希中,有一个键Week指向键值对的数组引用。所以这应该是一个哈希:

# create a Week hash from the even-sized list in $data->{Week}
my %week = @{$data->{Week}};

我只需要在代码中替换一些变量名称:

my @sum_IN1 = qw(IN1);
for my $num (keys %week) {

    my $found;
    my $sum = 0;

    for my $key (@sum_IN1) {

        next unless exists $week{$num}{$key};
        $sum   += $week{$num}{$key};
        $found = 1;
    }

    $week{$num}{Total_IN1} = $sum if $found;
}

print Dumper \%week;

工作正常!输出(顺序错误,但您可以轻松地sort):

$VAR1 = {
          '1238' => {
                      'OUT3FA_5' => 65,
                      'Total_IN1' => 85,
                      'OUT3A_5' => 20,
                      'OUT3-Fix' => 45,
                      'IN1' => 85
                    },
          '1226' => {
                      'OUT3FA_5' => 30,
                      'Total_IN1' => 40,
                      'OUT3A_5' => 5,
                      'OUT3-Fix' => 25,
                      'IN1' => 40
                    }
        };