CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Advanced:
convert array to nested hash

 



chasdavies
New User

May 20, 2010, 7:34 AM

Post #1 of 2 (1884 views)
convert array to nested hash Can't Post

I need help in determining the best method to convert an array to a nested hash.

Assume I have two arrays:


Code
 my @array1 = ("a", "b", "c", "d");  

my @array2 = ("a", "c", "e");



What I need to do is to to merge the two arrays into a hash table where I can assign some data to the leaf node (last element) of the tree. The hass needs to look like this:


Code
 my %hash = { 
'a' => {
'b' => {
'c' => {
d => 'some data'
}
},
'c' => {
'e' => 'some other data'
}
}
};



Any help on how to code this would be greatly appreciated.


shawnhcorey
Enthusiast


May 20, 2010, 12:17 PM

Post #2 of 2 (1877 views)
Re: [chasdavies] convert array to nested hash [In reply to] Can't Post

A little tricky: you have to keep track of the next to last item. Also, you will have problems if one sequence is the beginning subsequence of another, as in:

Code
@array1 = qw( a b c ); 
@array2 = qw( a b c d e );


Try:

Code
#!/usr/bin/perl 

use strict;
use warnings;

use Data::Dumper;

# Make Data::Dumper pretty
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Indent = 1;

# Set maximum depth for Data::Dumper, zero means unlimited
local $Data::Dumper::Maxdepth = 0;

my %hash = ();
my $c = 0;

store( qw( a b c d e ) );
store( qw( a c e ) );

print '%hash: ', Dumper \%hash;

sub store {

if( @_ ){
my $h = \%hash;
my $last = undef;
for my $k ( @_ ){
$last = $h;
$h->{$k} = {} unless exists $h->{$k};
$h = $h->{$k};
}
$last->{$_[-1]} = "some " . ( 'other ' x $c++ ) . "data";
}
}


__END__

I love Perl; it's the only language where you can bless your thingy.

Perl documentation is available at perldoc.perl.org. The list of standard modules and pragmatics is available in perlmodlib.

Get Markup Help. Please note the markup tag of "code".

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives