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

Re: Re: Re: Re: Looping through Multi Dimensional Hashes

by CodeJunkie (Monk)
on Jul 15, 2003 at 15:53 UTC ( #274456=note: print w/replies, xml ) Need Help??

in reply to Re: Re: Re: Looping through Multi Dimensional Hashes
in thread Looping through Multi Dimensional Hashes

Thanks! That code is complete genius and worked first time! I wish I could vote the same posts 10 times :-)

For anyone that wants to try the full program check this out:

#!c:\perl\bin\perl use strict; use warnings; my %category_hash; my %categories; # Build a hash containing all of our data records... while (<DATA>) { chomp; my %cat; @cat{'id','name','parent'} = split /,/; $categories{$cat{id}} = \%cat; } # ... and turn it into a tree foreach $_ (keys %categories) { if ($categories{$_}{parent}) { $categories{$categories{$_}{parent}}{children}{$_} = $categories{$_}; } else { $category_hash{$_} = $categories{$_}; } } # And now %category_hash is exactly the same as it was # in my previous post. Carry on with "show" as before. #You can then display the structure with code like this: show(\%category_hash, 0); sub show { my ($hash, $lvl) = @_; my $prefix = ' ' x $lvl; foreach (sort keys %$hash) { print "$prefix$_ : $hash->{$_}{name}\n"; show($hash->{$_}{children}, ++$lvl) if exists $hash->{$_}{children}; } } __DATA__ 1,whatever,0 2,something,1 3,something,1 4,somethingelse,1 5,another subcategory,2 6,something else,0 7,something else,0

Thanks again davorg


Log In?

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2020-05-29 21:05 GMT
Find Nodes?
    Voting Booth?
    If programming languages were movie genres, Perl would be:

    Results (171 votes). Check out past polls.