Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: How to transform a matrix into a hash??

by bobf (Monsignor)
on Feb 06, 2008 at 03:33 UTC ( [id://666455]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2024-04-25 21:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found