Thread "Beliebig" tiefes Hash mit keys aus Array erstellen
(22 answers)
Opened by shi8dao at 2011-06-21 08:35
Da wirst du eine weitere Struktur brauchen:
Code (perl): (dl
)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @var = ( ['Hund/Katze/Maus', 10], ['Hund/Katze/Igel', 9], ['Hund/Katze/Hase', 8], ['Wolf/Katze/Maus', 7], ['Wolf/Katze/Igel', 6], ['Wolf/Katze/Hase', 5], ['Hund/Tiger/Maus', 4], ['Hund/Tiger/Igel', 3], ['Hund/Tiger/Hase', 2], ['Wolf/Tiger/Maus', 1], ); my $hashref = {}; my $deep=[]; for my $v ( @var ) { my $val=$v->[1]; my @arr=split('/',$v->[0]); my $pos=0; my $tmp = \$hashref; for(@arr) { $$tmp->{summe}+=$val; push(@{$deep->[$pos]},$$tmp) if(!grep{$_ and $$tmp eq $_}@{$deep->[$pos]}); $tmp = \$$tmp->{childs}->{$_}; $pos++; } $$tmp->{summe}+=$val; push(@{$deep->[$pos]},$$tmp) if(!grep{$_ and $$tmp eq $_}@{$deep->[$pos]}); } #print "Summe Wolf/Katze = ".$hashref->{childs}->{Wolf}->{childs}->{Katze}->{summe}."\n"; #print Dumper($hashref); for my $pos (0..$#$deep) { print "POS($pos): "; print "$_->{summe}, " for(@{$deep->[$pos]}); print "\n"; } Last edited: 2011-06-21 15:36:21 +0200 (CEST) |