in reply to How to print a multi-level Hashes of Hashes and extract parts of it
Do you know about the ref function? You can use it to tell what kind of data is referenced, affecting how you handle it.
Here's a very quick-and-dirty subroutine show_this() that uses ref to recursively inspect the contents of your hash. As such, it's a primitive replacement for Data::Dumper:
#!/usr/bin/perl -w # use strict; use warnings; use Data::Dumper; my %singleLevelHash = (); my %multiLevelHash = ( 'firstSampleKey' => 'SampleValue', 'secondSampleKey' => { 'secondLevelSampleKey' => { 'thirdLevelSampleKeyOne' => 'thirdLevelSampleValue', 'thirdLevelSampleKeyTwo' => 'thirdLevelSampleValue', 'thirdLevelSampleKeyThree' => 'thirdLevelSampleValue', } } ); # print Dumper \%multiLevelHash; show_this(\%multiLevelHash); # foreach my $firstSampleKey ( sort keys %multiLevelHash ) { # print $firstSampleKey . "\n"; # foreach my $secondLevelSampleKey ( sort keys $multiLevelHash{$fi +rstSampleKey} ) { # print $secondLevelSampleKey . "\n"; # } # } sub show_this { my ($x) = @_; if (ref $x eq "") { printf " Value: '%s'\n", $x; } elsif (ref $x eq 'SCALAR') { printf " SCALAR ref: '%s'\n", $$x; } elsif (ref $x eq 'HASH') { print " HASH ref '$x':\n"; foreach my $key (keys %$x) { my $val = $x->{$key}; print " $key: "; show_this($val); } } elsif (ref $x eq 'ARRAY') { print " ARRAY re '$x':\n"; foreach my $val (@$x) { show_this($val); } } }
Hopefully that gives you an idea how to interpret a HASH ref, differently from a scalar value. Hint -- the solution is in the block:
foreach my $key (keys %$x) { ... }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How to print a multi-level Hashes of Hashes without the use of a module
by thanos1983 (Parson) on Jan 25, 2015 at 02:47 UTC |