From: dt on
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

From: xhoster on
"dt" <ppc(a)cheapbooks.com> wrote:
> 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

--
-------------------- http://NewsReader.Com/ --------------------
Usenet Newsgroup Service $9.95/Month 30GB
From: Mark Clements on
dt wrote:
> 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
From: Brian McCauley on
On 17 Feb, 08:08, Mark Clements <mark.clementsREMOVET...(a)wanadoo.fr>
wrote:
> dt wrote:
> > 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"}

> 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;

From: Mirco Wahab on
dt wrote:
> 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