简体   繁体   English

用Perl对哈希元素求和

[英]Sum hash elements with Perl

I have a Perl script that returns this hash structure : 我有一个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
                      }
                    ]
        };

What I'd like to do is, count the total of IN1 for each week, per example in this case it'll return: 我想做的是,计算每周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
                      }
                    ]
        };

And so on for each week. 以此类推。

How can I do this please? 我该怎么做? Any help would be appreciated. 任何帮助,将不胜感激。

Here is what I tried to do but it's not working : 这是我尝试做的,但是没有用:

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;
} 

First, your data structure is confusing. 首先,您的数据结构令人困惑。 'Week' is a reference to an array, some of whose elements are strings (such as '1238' ) and the rest of whose elements are hash references. 'Week'是对数组的引用,其中一些元素是字符串(例如'1238' ),而其他元素是哈希引用。

While Perl lets you get away with this, it would be a better design for each level of your data structure to hold only one kind of thing. 虽然Perl可以使您摆脱困境,但是对于只容纳一种东西的数据结构的每个级别来说,这都是一个更好的设计。 This is something to consider. 这是要考虑的事情。 However, I will leave it as is for now. 但是,我现在将其保留。

Here is a quick way to do it: 这是一种快速的方法:

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

use Data::Dumper;
print Dumper $VAR1;

Update: changed // to || 更新: //更改为|| as Mikko L suggested. 正如Mikko L建议的那样。

Explanation: 说明:

grep {ref $_} gets only the elements that are hash references out of the array. grep {ref $_}仅从数组中获取作为哈希引用的元素。

$_->{'IN1'} || 0 $_->{'IN1'} || 0 - If one of the hashes did not have 'IN1' , this would use zero instead. $_->{'IN1'} || 0如果其中一个哈希没有'IN1' ,则将使用零。 This is basically a check for the hash key being defined. 这基本上是对定义的哈希键的检查。 || is acceptable to do this for hash keys. 对于哈希键,可以这样做。 In other situations, however, you need the defined-or operator ( // , available from version 5.10 I believe). 但是,在其他情况下,则需要使用define-or运算符( // ,我相信可以从5.10版获得)。

$_->{'In1Total'} = $total+=$_->{'IN1'} || 0 $_->{'In1Total'} = $total+=$_->{'IN1'} || 0 this adds the current value of IN1 to the count, then puts the result into In1Total . $_->{'In1Total'} = $total+=$_->{'IN1'} || 0这会将IN1的当前值添加到计数中,然后将结果放入In1Total Admittedly this could be made a bit clearer by separating it into a couple of lines. 诚然,可以通过将其分成几行来使其更加清晰。

Update 2: fixed mistake Borodin pointed out. 更新2:修正了鲍罗丁指出的错误。

You need to keep a state variable holding the running total for each item in the array. 您需要保留一个状态变量,该变量保存数组中每个项目的运行总计。 I also suspect that you Week array is supposed to be a hash? 我还怀疑您的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;

output 产量

{
  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,
    },
  ],
}

Without seeing your code, it is hard to see why it is not working, but it may be because you are using a hash in your code, but the data structure returned is a hash reference. 没有看到您的代码,很难知道为什么它不起作用,但这可能是因为您在代码中使用了哈希,但是返回的数据结构是哈希引用。

Here is a version which should work (using hash references): 这是一个应该工作的版本(使用哈希引用):

#!/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;

Here's the output: 这是输出:

$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
                      }
                    ]
        };

Maybe you could learn something from a modification of your code, which, btw, works perfectly. 也许您可以从修改代码中学到一些东西,顺便说一句,它工作得很好。 The problem is that you treat the data structure wrong. 问题是您对待数据结构错误。 This: 这个:

# 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
        },
    ],
};

Is a hash reference. 是哈希引用。 In the referenced hash, there's a key Week that points to an array reference of key-value pairs. 在引用的哈希中,有一个键Week指向键-值对的数组引用。 So this should be a hash instead: 因此,这应该是一个哈希值:

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

The I just needed to replace some variable names in your code: 我只需要替换代码中的一些变量名即可:

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;

That works fine! 很好! Output (in wrong order, but you can sort it easily): 输出(顺序错误,但您可以轻松对其进行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
                    }
        };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM