0

我想从散列的散列中获取价值,但我没有。我的代码是:

sub test {
    my $filename = $_[0];
    open INFILE, ${filename} or die $!;
    my %hashCount;
    my @firstline = split('\t',<INFILE>);
    shift(@firstline);
    while (my $line = <INFILE>) 
    {
        my %temp;
        chomp($line);
        my @line = split('\t', $line);
        foreach my $cpt (1..$#line) {
            $temp{$firstline[$cpt-1]}=$line[$cpt];
        }
        $hashCount{$line[0]}={%temp};
    }
    return %hashCount;
}
sub get_hash_of_hash { 
    my $h = shift; 
    foreach my $key (keys %$h) { 
        if( ref $h->{$key}) { 
            get_hash_of_hash( $h->{$key} );
        } 
        else { 
            say $h->{$key};
        } 
    } 
}

当我显示我的哈希时:

$VAR10679 = 'M00967_43_1106_2493_14707';
$VAR10680 = {
          'A' => '1',
          'B' => '0',
          'C' => '1',
          'D' => '0',
          'E' => '0'
        };

我的第一个函数返回我的哈希值,我用第二个函数得到我的特定值。所以我想获得这样的价值:

my %hashTest = test("FILE.txt"); get_hash_of_hash(%hashTest,"M00967_43_1106_2493_14707","A") //return value '1'

4

3 回答 3

1

您的哈希值适用references于哈希值。

您可以像这样访问它们:

$hashTest{'M00967_43_1106_2493_14707'}{'A'};

有关更多信息,请参见perlref

于 2013-07-15T12:28:14.100 回答
1

You can either access nested elements like

$hash{keyA}{keyB}

or we can write a function that walks the data structure, like

sub walk {
  my ($hashref, @keys) = @_;
  my $pointer = $hashref;
  for my $key (@keys) {
    if (exists $pointer->{$key}) {
      $pointer = $pointer->{$key};
    } else {
      die "No value at ", join "->", @keys;
    }
  }
  return $pointer;
}

which can be used like

my %hash = (
  'M00967_43_1106_2493_14707' => {
      'A' => '1',
      'B' => '0',
      'C' => '1',
      'D' => '0',
      'E' => '0'
  },
);
say walk(\%hash, 'M00967_43_1106_2493_14707', 'A');

Note: When using Data::Dumper, pass references to the Dump function:

print Dump \%hash; # not print Dump %hash

This is neccessary to show the correct data structure.

于 2013-07-15T13:38:24.343 回答
0

使用这个子程序..

sub get_hash_of_hash { 
        my $h = shift; 
        foreach my $key (keys %$h) { 
            if( ref $h->{$key}) { 
                get_hash_of_hash( $h->{$key} );
            } 
            else { 
                print $h->{$key};
            } 
        } 
    }
于 2013-07-15T12:33:30.007 回答