thanos1983 has asked for the wisdom of the Perl Monks concerning the following question:
Hello Monks,
Although that this seems with a very common question I can not find solution to my problem. I have a hash that contains multiple levels and I am trying to extract the data of the final level.
I want to use for loops to reach the final level and then store the data to one level hash.
I have been reading online the perldoc Access and Printing of a HASH OF HASHES. Even I found a similar question Traverse an unknown multi-dimensional hash but it is not exactly what I want.
On the sample of code that I have created I can see the path of the hash clearly by using Data::Dumper but I want to use foreach loops so I can reach the final stage of my complex hash and extract the data to a simple single level hash.
Update: The %singleLevelHash = (); that I have defined I wan to contain the last level of data.
Update 2: I tried to use everybodies solution to get the desired output, but still I can not figure it how to do it. I will update also the title of my question.
I am trying to extract the final part of hash as given in the sample code under.
Sample of desired output:
%singleLevelHash = ( 'thirdLevelSampleKeyOne' => 'thirdLevelSampleValue', 'thirdLevelSampleKeyTwo' => 'thirdLevelSampleValue', 'thirdLevelSampleKeyThree' => 'thirdLevelSampleValue', );
This is the reason that I wanted to use the foreach loop. Sample of my code provided under.
Sample of code:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %singleLevelHash = (); my %multiLevelHash = ( 'firstSampleKey' => 'SampleValue', 'secondSampleKey' => { 'secondLevelSampleKey' => { 'thirdLevelSampleKeyOne' => 'thirdLevelSampleValue', 'thirdLevelSampleKeyTwo' => 'thirdLevelSampleValue', 'thirdLevelSampleKeyThree' => 'thirdLevelSampleValue', } } ); print Dumper \%multiLevelHash; foreach my $firstSampleKey ( sort keys %multiLevelHash ) { print $firstSampleKey . "\n"; foreach my $secondLevelSampleKey ( sort keys $multiLevelHash{$firs +tSampleKey} ) { print $secondLevelSampleKey . "\n"; } } __DATA__ $VAR1 = { 'firstSampleKey' => 'SampleValue', 'secondSampleKey' => { 'secondLevelSampleKey' => { 'thirdLev +elSampleKeyOne' => 'thirdLevelSampleValue', 'thirdLev +elSampleKeyThree' => 'thirdLevelSampleValue', 'thirdLev +elSampleKeyTwo' => 'thirdLevelSampleValue' } } }; firstSampleKey Type of argument to keys on reference must be unblessed hashref or arr +ayref at hash.pl line 21.
Any suggestions are much appreciated.
|
|---|