Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: How to print a multi-level Hashes of Hashes without the use of a module

by golux (Chaplain)
on Jan 25, 2015 at 01:47 UTC ( [id://1114403]=note: print w/replies, xml ) Need Help??


in reply to How to print a multi-level Hashes of Hashes and extract parts of it

Hi thanos1983,

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) { ... }
say  substr+lc crypt(qw $i3 SI$),4,5

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

    Hello golux,

    Thank you for your time and effort reading and replying to my post. I will try to play around with your suggesting to find my solution.

    I was not aware of the ref function, thanks for pointing this out.

    Seeking for Perl wisdom...on the process of learning...not there...yet!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1114403]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (2)
As of 2024-04-20 03:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found