Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: generating hash from array

by pg (Canon)
on Oct 21, 2005 at 17:20 UTC ( [id://502078]=note: print w/replies, xml ) Need Help??


in reply to generating hash from array

Change your data structure a little bit (a better one, so that all levels are consistant), you can use some more generic code:

use warnings; use strict; use Data::Dumper; my @array = qw/ comp1-cmd1-test1 comp1-cmd1-test2 comp1-cmd2-test1 comp2-cmd1-test1 comp2-cmd1-test2 comp3-cmd1-test1/; my $hash = {}; for my $element (@array) { my @stuffs = split /-/, $element; insert($hash, \@stuffs); } print Dumper($hash); sub insert { my ($hash, $stuffs) = @_; my $first_element = shift @$stuffs; $hash->{$first_element} = {} if (!defined($hash->{$first_element}) +); insert($hash->{$first_element}, $stuffs) if (@$stuffs); }

This gives:

$VAR1 = { 'comp2' => { 'cmd1' => { 'test1' => {}, 'test2' => {} } }, 'comp3' => { 'cmd1' => { 'test1' => {} } }, 'comp1' => { 'cmd2' => { 'test1' => {} }, 'cmd1' => { 'test1' => {}, 'test2' => {} } } };

Log In?
Username:
Password:

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

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

    No recent polls found