Thread Trick zum vernknüpfen von Hashes (5 answers)
Opened by Froschpopo at 2008-07-08 10:47

murphy
 2008-07-08 18:13
#111944 #111944
User since
2004-07-19
1776 Artikel
HausmeisterIn
[Homepage]
user image
Ich würde mir einfach eine Hilfsfunktion definieren:
Code (perl): (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Update a hash by adding or replacing mappings. Hash references
# stored in the top level hash can be updated recursively, if desired.
# Params:
#   %h      = The hash to modify
#   $depth = Recursion depth.
#   @kv     = New key value pairs.
sub hpush(\%$@);
sub hpush(\%$@) {
    my ($h, $depth, @kv) = @_;
    
    while (@kv) {
        my ($k, $v) = splice @kv, 0, 2;
        
        if ($depth > 0 and ref($h->{$k}) eq 'HASH' and ref($v) eq 'HASH') {
            hpush %{$h->{$k}}, $depth - 1, %{$v};
        }
        else {
            $h->{$k} = $v;
        }
    }
}


Anwendungsbeispiel:
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
use Data::Dumper;

my %h = (
  foo => 42,
  bar => {
    x => {
      u => 1,
      v => 2
    },
    y => 'blubb'
  }
);

print Dumper \%h;

hpush %h, 1, (
  baz => 23,
  bar => {
    x => {
      w => 3
    },
    z => 'blargh'
  }
);


print Dumper \%h;
When C++ is your hammer, every problem looks like your thumb.

View full thread Trick zum vernknüpfen von Hashes