Domanda

I'm trying to take the value from the hash and use it as the key for the next level hash, this code works, but I am thinking there has to be a better way to do this.

Is there a way to avoid the K* array variables?

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 looks like this:

$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'
                }
            }
        }
    }
};

Thanks!

È stato utile?

Soluzione

Keys aren't sorted, so the "first key" won't always be the same.

That said, if you want to compact this a bit, the following should work:

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

This is ugly and I would not want to be the guy who comes after you reading this.

Keys will work on hash refs as well as hashes starting with Perl 5.14. If you're older than that, you'll just have to dereference into a full on hash.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top