嵌套的Perl哈希

时间:2014-04-24 21:41:54

标签: perl hash casting nested

我正在尝试从哈希中获取值并将其用作下一级哈希的键,此代码可以正常工作,但我认为必须有更好的方法来执行此操作。

有没有办法避免K *数组变量?

my @key = keys %data3;
my $deviceType = $key[0];
my @K = keys %{$data3 {$deviceType} };  ## Uber Ugly, find a better way.
my $measInfoID = $K[0]; 
my @K1 = keys %{$data3 {$deviceType} {$measInfoID}};
my $deviceID = $K1[0];
my @K2 = keys %{$data3 {$deviceType} {$measInfoID} {$deviceID}};
my $location = $K2[0];
my @K3 = %{$data3 {$deviceType} {$measInfoID} {$deviceID} {$location}};
my $measObjectLdn = $K3[0];

print ("Data: $deviceType, $measInfoID, $deviceID, $location, $measObjectLdn\n");
    foreach my $m ( keys %{ $data3 {$deviceType} {$measInfoID} {$deviceID} {$location} {$measObjectLdn} } ){
  print("OK: $m\n");
}

%data3看起来像这样:

$VAR1 = 'NTHLRFE';
$VAR2 = {
    'DIA' => {
        'NJBB-HLR-2' => {
            'NJBB' => {
                'LTE-1/DIA-1' => {
                    'DiaUnknownAVPs' => '0',
                    'DiaCerRejSysInOvl' => '0',
                    'DiaProtocolErrors' => '0',
                    'DiaWrongProtType' => '0',
                    'DiaMessageRcvd' => '0',
                    'DiaOctetSent' => '0',
                    'DiaCerRejPrNtInWhtLst' => '0',
                    'DiaOctetRcvd' => '0',
                    'DiaMessageDscrd' => '0',
                    'DiaCerRejConAvailable' => '0',
                    'DiaMessageSent' => '0',
                    'DiaCerRejMaxConExcd' => '0'
                }
            }
        }
    }
};

谢谢!

1 个答案:

答案 0 :(得分:1)

键没有排序,所以"第一个键"不会永远不变。

那就是说,如果你想稍微压缩一下,以下应该有效:

my $deviceType = (keys %data3)[0];
....
my $measInfoID = (keys $data3{$deviceType})[0];
....
my $deviceID = (keys $data3{$deviceType}{$measInfoID})[0];

这很难看,我不想成为你读完之后来的人。

Keys将使用散列引用以及从Perl 5.14开始的散列。如果您的年龄大于此值,则只需将其取消引用为完整哈希值。