Perl的:一个复杂的哈希生成内部数组(Perl: Generating Arrays inside

2019-06-25 04:54发布

在寻求使我的数据更易于访问,我想存储在一个复杂的哈希我表格数据。 我想长出“HoHoHoA”为脚本遍历我的数据。 按照在“perldsc”的指导方针:

push @ { $hash{$column[$i]}{$date}{$hour} }, $data[$i];

该脚本编译并没有问题,运行,但不会不添加任何数据的哈希:

print $hash{"Frequency Min"}{"09/07/08"}{"15"}; 

返回即使键应该存在什么。 运行“存在”散列表明,它不存在。

我正在读的数据文件是这样的:

DATE       TIME     COLUMN1 COLUMN2 COLUMN3...    
09/06/2008 06:12:56 56.23   54.23   56.35...
09/06/2008 06:42:56 56.73   55.28   54.52...
09/06/2008 07:12:56 57.31   56.79   56.41...
09/06/2008 07:42:56 58.24   57.30   58.86...
.
.
.

我想组一起每一列的在任何给定日期和小时的阵列三个散列为{COLUMN},{DATE}和{HOUR}的值,因此。

所产生的结构如下所示:

%monthData = (
               "COLUMN1" => {
                                    "09/06/2008" => {
                                                      "06" => [56.23,56.73...],
                                                      "07" => [57.31,58.24...]
                                                    }
                            },
               "COLUMN2" => {
                                    "09/06/2008" => {
                                                      "06" => [54.23,55.28...],
                                                      "07" => [56.79,57.30...]
                                                    }
                            },
               "COLUMN3" => {
                                    "09/06/2008" => {
                                                      "06" => [56.35,54.52...],
                                                      "07" => [56.41,58.86...]
                                                    }
                            }
             );

看看我的代码:

use feature 'switch';
open DATAFILE, "<", $fileName or die "Unable to open $fileName !\n";

    my %monthData;

    while ( my $line = <DATAFILE> ) {

        chomp $line;

        SCANROWS: given ($row) {

            when (0) { # PROCESS HEADERS

                @headers = split /\t\t|\t/, $line;
            }

            default {

                @current = split /\t\t|\t/, $line;
                my $date =  $current[0];
                my ($hour,$min,$sec) = split /:/, $current[1];

                # TIMESTAMP FORMAT: dd/mm/yyyy\t\thh:mm:ss

                SCANLINE: for my $i (2 .. $#headers) {

                    push @{ $monthData{$headers[$i]}{$date}{$hour} }, $current[$i];

                }
            }
        }
    }

    close DATAFILE;

    foreach (@{ $monthData{"Active Power N Avg"}{"09/07/08"}{"06"} }) {
        $sum += $_;
        $count++;
    }

    $avg = $sum/$count; # $sum and $count are not initialized to begin with.
    print $avg; # hence $avg is also not defined.

希望我的需要是非常明显的。 我怎么可以追加值,这些子哈希里的数组?

Answer 1:

这应该为你做它。

#!/usr/bin/perl

use strict;
use warnings;

use List::Util qw/sum/;
sub avg { sum(@_) / @_ }

my $fileName = shift;

open my $fh, "<", $fileName
    or die "Unable to open $fileName: $!\n";

my %monthData;

chomp(my @headers = split /\t+/, <$fh>);

while (<$fh>) {
    chomp;
    my %rec;
    @rec{@headers} = split /\t+/;
    my ($hour) = split /:/, $rec{TIME}, 2;

    for my $key (grep { not /^(DATE|TIME)$/ } keys %rec) {
        push @{ $monthData{$key}{$rec{DATE}}{$hour} }, $rec{$key};
    }
}

for my $column (keys %monthData) {
    for my $date (keys %{ $monthData{$column} }) {
        for my $hour (keys %{ $monthData{$column}{$date} }) {
            my $avg = avg @{ $monthData{$column}{$date}{$hour} };
            print "average of $column for $date $hour is $avg\n";
        }
    }
}

事情要注意:

  • 严格和警告编译指示
  • 列表::的Util模块获得求和函数
  • 把一个阵列中的标量上下文来获得数组中的项的数量(在平均函数)
  • 打开更安全的以上三个参数版本
  • 词法文件句柄(而不是旧的裸字样式文件句柄)
  • 第一读取头的循环外,以避免必须具有在其内部的特殊逻辑
  • 使用散列切片来获取文件数据到一个结构化记录
  • 避免与第三个参数拆分时间超过必要的拆分
  • 通过仅指定变量避免无用的变量,我们要在列表分配赶上
  • 使用grep的 ,以防止被放在%DATE和TIME键monthData
  • 嵌套的每个处理哈希水平环


Answer 2:

我希望下面的程序填入你想要的数据结构:

#!/usr/bin/perl                        

use strict;
use warnings;
use Data::Dumper;

open my $fh, '<', 'input' or die $!;

my @headers;
for ( split /\t/, ~~ <$fh> ) {
    chomp;
    push @headers, $_ unless /^\t?$/;
}

my %monthData;
while (<$fh>) {
    my @line;
    for ( split /\t/ ) {
        chomp;
        push @line, $_ unless /^\t?$/;
    }

    for my $i ( 2 .. $#headers ) {
        my ($hour) = split /:/, $line[1];
        push @{ $monthData{ $headers[$i] }->{ $line[0] }->{$hour} }, $line[$i];
    }
}

print Dumper \%monthData;


Answer 3:

以下是我会写一个程序来做到这一点。

#! /usr/bin/env perl
use strict;
use warnings;
use 5.010; # for say and m'(?<name>)'

use YAML;
use Data::Dump 'dump';

my(%data,%original);
while( my $line = <> ){
  next unless $line =~ m'
    ^ \s*
      (?<day>   0?[1-9] | [12][0-9] | 3[0-1] ) /
      (?<month> 0?[1-9] | 1[0-2] ) /
      (?<year>  [0-9]{4} )
      \s+
      (?<hour>   0?[1-9] | 1[0-9] | 2[0-4] ) :
      (?<minute> 0?[1-9] | [1-5][0-9] ) :
      (?<second> 0?[1-9] | [1-5][0-9] )
      \s+
      (?<columns> .* )
  'x;
  my @columns = split ' ', $+{columns};

  push @{
    $data{ $+{year}  }
         { $+{month} }
         { $+{day}   }
         { $+{hour}  }
  }, \@columns; # or [@columns]

  # If you insist on having it in that data structure you can do this:
  my $count = 1;
  my $date = "$+{day}/$+{month}/$+{year}";
  for my $column ( @columns ){
    my $col = 'COLUMN'.$count++;
    push @{ $original{$col}{$date}{$+{hour}} }, $column;
  }
}

say Dump \%data, \%original; # YAML
say dump \%data, \%original; # Data::Dump

鉴于此输入

DATE       TIME     COLUMN1 COLUMN2 COLUMN3
09/06/2008 06:12:56 56.23   54.23   56.35
09/06/2008 06:42:56 56.73   55.28   54.52
09/06/2008 07:12:56 57.31   56.79   56.41
09/06/2008 07:42:56 58.24   57.30   58.86

任一“ perl program.pl datafile ”或“ perl program.pl < datafile

Yamla

---
2008:
  06:
    09:
      06:
        -
          - 56.23
          - 54.23
          - 56.35
        -
          - 56.73
          - 55.28
          - 54.52
      07:
        -
          - 57.31
          - 56.79
          - 56.41
        -
          - 58.24
          - 57.30
          - 58.86
---
COLUMN1:
  09/06/2008:
    06:
      - 56.23
      - 56.73
    07:
      - 57.31
      - 58.24
COLUMN2:
  09/06/2008:
    06:
      - 54.23
      - 55.28
    07:
      - 56.79
      - 57.30
COLUMN3:
  09/06/2008:
    06:
      - 56.35
      - 54.52
    07:
      - 56.41
      - 58.86

数据::转储

(
  {
    2008 => {
          "06" => {
                "09" => {
                      "06" => [["56.23", "54.23", "56.35"], ["56.73", "55.28", "54.52"]],
                      "07" => [["57.31", "56.79", "56.41"], ["58.24", "57.30", "58.86"]],
                    },
              },
        },
  },
  {
    COLUMN1 => {
                 "09/06/2008" => { "06" => ["56.23", "56.73"], "07" => ["57.31", "58.24"] },
               },
    COLUMN2 => {
                 "09/06/2008" => { "06" => ["54.23", "55.28"], "07" => ["56.79", "57.30"] },
               },
    COLUMN3 => {
                 "09/06/2008" => { "06" => ["56.35", "54.52"], "07" => ["56.41", "58.86"] },
               },
  },
)


文章来源: Perl: Generating Arrays inside a Complex Hash