perlhash-of-hashes

Referring to a chain of hash keys in a Perl hash of hashes


I have a hash of hashes storing data like so

our %deviceSettings = (
  BB => {
          EUTRA => {
            DL => { CPC => "NORM", PLCI => { CID => 88 }, ULCPc => "NORM" },
            UL => {
                    REFSig  => { DSSHift => 2, GRPHopping => 1, SEQHopping => 1 },
                    SOFFset => 0,
                  },
          },
        },
  ...
);

I can walk the structure and find a particular key, say CID, and retrieve its value and store the 'path' in an array ('BB', 'EUTRA', 'DL', 'PLCI').

I can also explicitly set a value, like this

$deviceSettings_ref->{BB}{EUTRA}{DL}{PLCI}{CID} = 99

But I want to know how to set a value programatically using a discovered path.


Solution

  • You can walk up the hash using a placeholder $hashref:

    my $hashref = \%deviceSettings;
    
    $hashref = $hashref->{$_} for qw(BB EUTRA DL PLCI);
    $hashref->{CID} = 'My New Path';
    
    use Data::Dump;
    dd \%deviceSettings;
    

    Outputs:

    {
      BB => {
              EUTRA => {
                DL => { CPC => "NORM", PLCI => { CID => "My New Path" }, ULCPc => "NORM" },
                UL => {
                        REFSig  => { DSSHift => 2, GRPHopping => 1, SEQHopping => 1 },
                        SOFFset => 0,
                      },
              },
            },
    }