Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Traverse an unknown multi-dimensional hash

by GrandFather (Saint)
on Jul 12, 2007 at 10:46 UTC ( #626192=note: print w/replies, xml ) Need Help??


in reply to Traverse an unknown multi-dimensional hash

Recursion is the trick:

use strict; use warnings; my %hash = ( 1 => { a => { i => 'level 3', ii => 'level 3', iii => 'level 3', }, b => { i => 'level 3', ii => 'level 3', iii => 'level 3', }, }, 2 => {a => 'level2', b => 'level2'}, 3 => 'level 1', 4 => 'level 1', ); print dumpHash(\%hash); sub dumpHash { my ($element, $indent) = @_; $indent ||= ''; return "$indent$element\n" unless 'HASH' eq ref $element; my $str= ''; for my $key (sort keys %$element) { $str .= "$indent$key =>\n"; $str .= dumpHash ($element->{$key}, $indent . ' '); } return $str; }

Prints:

1 => a => i => level 3 ii => level 3 iii => level 3 b => i => level 3 ii => level 3 iii => level 3 2 => a => level2 b => level2 3 => level 1 4 => level 1

DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: Traverse an unknown multi-dimensional hash
by Anonymous Monk on Jul 27, 2012 at 18:05 UTC
    how would i do something like 1 => a =>i =>level 3
    1=> a=> =>ii => level3
    1=>a=>iii=>level3
    etc.... Please help
      How would i print the output like this : 1 => a =>i =>level 3 1=> a=> =>ii => level3 1=>a=>iii=>level3 etc I could not workout the code to go back to the start and traverse back.
        ub dumpHash { my ($element, $indent) = @_; $indent ||= ''; return " = $indent$element\n" unless 'HASH' eq ref $element; my $str= ''; for my $key (sort keys %$element) { $str .= "$indent$key :"; $str .= dumpHash ($element->{$key}, $indent . ' '); } return $str;
        output :
        toplevel-1 : sublevel1a : = value-1a sublevel1b : = value-1b toplevel-2 : sublevel1c : value-1c.1 : = replace +ment-1c.1 value-1c.2 : = replacement-1c.2 sublevel1d : = value-1d
        but i want
        toplevel-1 : sublevel1a : = value-1a toplevel-1 : sublevel1b : = value-1b

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (1)
As of 2022-01-16 22:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (50 votes). Check out past polls.

    Notices?