convert string of keys to multidimensional hash

D

dt

how do I do this:

convert a string such as "dim1:dim2:dim3"
or array ("dim1", "dim2", "dim3")

to a hash like:
$hash{"dim1"}{"dim2"}{"dim3"}

any help is appreciated
 
X

xhoster

dt said:
how do I do this:

convert a string such as "dim1:dim2:dim3"
or array ("dim1", "dim2", "dim3")

to a hash like:
$hash{"dim1"}{"dim2"}{"dim3"}

any help is appreciated

You want to convert data into source-code? Are you sure this is what
you really want to do?

Xho
 
M

Mark Clements

dt said:
how do I do this:

convert a string such as "dim1:dim2:dim3"
or array ("dim1", "dim2", "dim3")

to a hash like:
$hash{"dim1"}{"dim2"}{"dim3"}

I'm not entirely sure what you're after, but:

F:\Documents and Settings\Mark3>cat hash.pl
use strict;
use warnings;

use Data::Dumper;

my $string = "dim1:dim2:dim3";

my @items = split /:/,$string;

my %hash = ();

my $lastItem = \%hash;

foreach my $item(@items){
my $newItem = {};
$lastItem->{$item} = $newItem;
$lastItem = $newItem;


}

print Dumper \%hash;


__END__

F:\Documents and Settings\Mark3>perl hash.pl
$VAR1 = {
'dim1' => {
'dim2' => {
'dim3' => {}
}
}
};

may get you started.

Mark
 
B

Brian McCauley

my %hash = ();

my $lastItem = \%hash;

foreach my $item(@items){
my $newItem = {};
$lastItem->{$item} = $newItem;
$lastItem = $newItem;

}

This is a very common problem and there's a very simple way to do it
avoiding the last empty hash:

my $lastItem = \\%hash;
$lastItem = \$$lastItem->{$_} for @items;
 
M

Mirco Wahab

dt said:
how do I do this:

convert a string such as "dim1:dim2:dim3"
or array ("dim1", "dim2", "dim3")

to a hash like:
$hash{"dim1"}{"dim2"}{"dim3"}

any help is appreciated

after reading Brians excellent reply
(which was somehow new for me), I'd
like to add 2 "functional forms" to
the discussion (recursive), one
ends up with 'undef' on the chain,
the other with a clean hash ref:

...

# end up w/hash ref:
sub rh2arr { rh2arr($_[0]->{$_[1]}={}, @_[2..@_-1]) if @_>1 }

#end up w/undef
sub rrh2arr { rrh2arr(\${$_[0]}->{$_[1]}, @_[2..@_-1]) if @_>1 }

# usage
my @arr = qw'dim1 dim2 dim3';
my (%hash1, %hash2);

rh2arr \%hash1, @arr;
print Dumper \%hash1;

rrh2arr \\%hash2, @arr; # learned \\this from Brian's post ;-)
print Dumper \%hash2;

...


Regards (and thanks to Brian)

Mirco
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top