构造散列哈希然后打印

时间:2015-07-30 14:13:14

标签: perl

有人可以帮我理解我在这里做错了吗?

#!/usr/bin/perl
use MIME::Lite;
use Sys::Hostname;

use strict;
use Time::Local;
use warnings;

my %resultMap=();
my @myarray = (
'a',
'b',
'c',
'd'
);

my %ha = (
            A => {'UserNum' => 1, 'Password' => 'abc', 'Server' => 'AAAA',  'Database' => 'BBB'},
            B => {'UserNum' => 2, 'Password' => 'abc', 'Server' => 'AAAA',  'Database' => 'BBB'}                                    
          );    

for my $region ( keys %ha ) {

    my %hashone=();  
    foreach (@myarray) {    
        my $myStr =  $_ ;   
        $hashone {$myStr} = $ha{'UserNum'};

        print "$myStr ---> $hashone{$myStr}\n";
    }

    $resultMap{$region} = { %hashone }; 

}

for my $regionKey (keys %resultMap ){
    print "Key -$regionKey\n";      
    for my $table ( keys %{ $resultMap{$regionKey} } ) {
        my %counthash = $resultMap{$regionKey};
         print "$regionKey : $counthash{$table}\n";
    }
}

我真的不知道我在这里做错了什么。我期待在打印出错后输出中的数字。

    Use of uninitialized value in concatenation (.) at testHash.pl line 29.
    a --->
    Use of uninitialized value in concatenation (.) at testHash.pl line 29.
    b --->
    Use of uninitialized value in concatenation (.) at testHash.pl line 29.
    c --->
    Use of uninitialized value in concatenation (.) at testHash.pl line 29.
    d --->
    Use of uninitialized value in concatenation (.) at testHash.pl line 29.
    a --->
    Use of uninitialized value in concatenation (.) at testHash.pl line 29.

1 个答案:

答案 0 :(得分:2)

这是因为你有一个比你想象的更深层次的嵌套结构。我已用# <-- here标记了我已做出更改的行。第二个更改(第39行)是因为$resultMap{$regionKey}本身包含一个哈希,所以要复制它,你需要通过用哈希的外接运算符(%{})包围它来取消引用它。

#!/usr/bin/perl
use MIME::Lite;
use Sys::Hostname;

use strict;
use Time::Local;
use warnings;

my %resultMap=();
my @myarray = (
'a',
'b',
'c',
'd'
);

my %ha = (

            A => {'UserNum' => 1, 'Password' => 'abc', 'Server' => 'AAAA',  'Database' => 'BBB'},
            B => {'UserNum' => 2, 'Password' => 'abc', 'Server' => 'AAAA',  'Database' => 'BBB'}
          );

for my $region ( keys %ha ) {

    my %hashone=();
    foreach (@myarray) {
        my $myStr =  $_ ;
        $hashone{$myStr} = $ha{$region}->{'UserNum'}; # <-- here

        print "$myStr ---> $hashone{$myStr}\n";
    }

    $resultMap{$region} = { %hashone };

}

for my $regionKey (keys %resultMap ){
    print "Key -$regionKey\n";
    for my $table ( keys %{ $resultMap{$regionKey} } ) {
        my %counthash = %{$resultMap{$regionKey}};  # <-- here
         print "$regionKey : $counthash{$table}\n";
    }
}