4

I have the following text file.

foo1    bam
foo1    bam
foo2    bam
foo1    zip
foo2    boo
foo1    zip
foo3    zip

I would like to make a Hash of Hashes where KEY1 is column one, KEY2 is the sound it makes (column two): bam, zip, or boo, and the VALUE is the number of occurrences of that sound. Such that the data structure is like this:

$VAR1 = {
      'foo1' => {
                         'bam' => [
                                    2
                                  ],
                         'zip' => [
                                  2
                                ],
                       },
      'foo2' => {
                        'bam' => [
                                 1
                               ],
                        'boo' => [
                                 1
                               ],
                      },
        'foo3' => {
                        'zip' => [
                                  1
                                ],
                    }
         }

Here's what I have so far

use strict; use warnings;    
open(my $fh, '<', 'file.txt') or die $!;
my %HoH;
while(<$fh>){
    chomp;
    my @cols = split(/\t/, $_);
    my $KEY1 = $cols[0];
    my $KEY2 = $cols[1];
    push( @{$HoH{$KEY1}{$KEY2}}, 1); # This actually creates a hash of hash of arrays
}

my %HoH_final;
foreach my $KEY1 (%HoH) {
    foreach my $KEY2 (keys %HoH{$KEY1}){
    my $count = scalar @{$HoH{$KEY1}{$KEY2}}; # get the size of that array
        push( @{$HoH_final{$KEY1}{$KEY2}}, $count);
   }
}

What do you think?

4

3 回答 3

5

你真的不想要下面的数据结构吗?

{
   'foo1' => {
      'bam' => 2,
      'zip' => 2,
   },
   ...
}

如果是这样,

while (<$fh>) {
    chomp;
    my @cols = split /\t/;
    ++$HoH{ $cols[0] }{ $cols[1] };
}

如果你真的想要单元素数组,

while (<$fh>) {
    chomp;
    my @cols = split /\t/;
    ++$HoH{ $cols[0] }{ $cols[1] }[0];
}
于 2013-04-21T02:33:58.910 回答
3

实际上这会解决问题

 perl -F'\t' -ane'$h{$F[0]}{$F[1]}++'

如果你想看到结果

 perl -MData::Dumper -F'\t' -ane'$h{$F[0]}{$F[1]}++}{print Dumper(\%h)'
于 2013-04-21T11:13:27.150 回答
3

每个二级键指向一个arrayref而不是数字是否有原因?我建议这样做:

while(<$fh>){
    chomp;
    my @cols = split(/\t/, $_);
    $HoH{ $cols[0] }{ $cols[1] }++;
}

这将++在遇到每个二级键时增加 () 值。

于 2013-04-21T02:36:08.777 回答