Thread "Beliebig" tiefes Hash mit keys aus Array erstellen (22 answers)
Opened by shi8dao at 2011-06-21 08:35

topeg
 2011-06-21 14:56
#149825 #149825
User since
2006-07-10
2611 articles
BenutzerIn

user image
Meinst du so was?

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
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my @var = (
  ['Hund/Katze/Maus', 10],
  ['Hund/Katze/Ratte', 9],
  ['Hund/Katze/Hase',  8],
  ['Wolf/Katze/Maus',  7],
  ['Wolf/Katze/Ratte', 6],
  ['Wolf/Katze/Hase',  5],
  ['Hund/Tiger/Maus',  4],
  ['Hund/Tiger/Ratte', 3],
  ['Hund/Tiger/Hase',  2],
  ['Wolf/Tiger/Maus',  1],
);

my $hashref = {};
for my $v ( @var )
{
  my $val=$v->[1];
  my @arr=split('/',$v->[0]);

  my $tmp = \$hashref;
  for(@arr)
  {
    $$tmp->{summe}+=$val;
    $tmp = \$$tmp->{childs}->{$_};
  }
  $$tmp->{summe}+=$val;
}

print Dumper($hashref);

# zugriff:

print "Summe Wolf/Katze = ".$hashref->{childs}->{Wolf}->{childs}->{Katze}->{summe}."\n";

View full thread "Beliebig" tiefes Hash mit keys aus Array erstellen