in reply to How to transform a matrix into a hash??

IMO, Data::Diver is definitely the way to go here. No fuss, no muss - just DWIMery.

use strict; use warnings; use Data::Diver qw( DiveVal ); use Data::Dumper; my $aokeys = [ [ 'a', 'b', 'c' ], [ 'a', 'b', 'd' ], [ 'b', 'b', 'b' ], ]; my $href = {}; foreach my $key_aref ( @$aokeys ) { DiveVal( $href, @$key_aref ) = 1; } print Dumper $href;
$VAR1 = { 'a' => { 'b' => { 'c' => 1, 'd' => 1 } }, 'b' => { 'b' => { 'b' => 1 } } };

Replies are listed 'Best First'.
Re^2: How to transform a matrix into a hash??
by yocoim (Initiate) on Feb 06, 2008 at 19:47 UTC
    Thanks all for your suggestions!
    I never used 'eval', but from what I've read, it seems like a good thing!
    The recursive way of doing it has nothing wrong, but I was wondering if there were other ways - to learn new tricks :)
    Thanks again! Maybe I can actually post the recursive way:
    my @array_2D = blablabla my ($tree, $tmp); foreach my $row (@array){ $tmp = extend_MTree($row); $tree = add($tmp, $tree); } $tree now contains the hash! sub extend_MTree($) { my ($a) = @_; my %H_tmp; if( $#{$a} == -1) { return 1; } my $elmt = shift @$a; $H_tmp{$elmt} = extend_MTree($a); return \%H_tmp; } sub add() { my ($tmp, $res) = @_; foreach my $key (keys %$tmp) { # this is a new path, add here and leave if(!defined($res->{$key})) { $res->{$key} = $tmp->{$key}; return $res; } # this part of the path exists, recurse $res->{$key} = add($tmp->{$key}, $res->{$key}); return $res; }