10 Einträge, 1 Seite |
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
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my $foo = &splitme("foo/lol" => "blub","foo/lol/bla" => "grml");
print Dumper($foo);
sub splitme {
my %hash = @_;
my $return;
foreach my $element(keys %hash) {
my @split=split(/\//,$element);
my $last = { };
$return = $last;
foreach my $i (0..$#split){
my $part = $split[$i];
if ($i == $#split){
$last->{$part} = $hash{$element};
}else{
$last->{$part} = { };
}
$last = $last->{$part};
}
}
return $return;
}
my $foo = &splitme("foo/lol" => "blub","foo/lol/bla" => "grml");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
sub splitme {
my (%pairs) = @_;
my $hash = {};
for my $keypath (keys %pairs) {
my @paths = split m#/#, $keypath;
my $value = $pairs{$keypath};
make_hash($hash, $value, @paths);
}
return $hash;
}
sub make_hash {
my ($hash, $value, @paths) = @_;
my $ref = \$hash;
for (@paths) {
$ref = \$$ref->{$_};
}
$$ref = $value;
}
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my $bla = Container->new();
$bla->blub("foo/bar" => "eins");
$bla->blub("foo/bla" => "zwei");
my $foo = $bla->getValue();
print Dumper $foo;
package Container;
sub new {
my $class = shift;
my $self = {};
bless $self, $class;
return $self;
}
sub blub {
my $self = shift;
$self->{Hash} = {};
my %foo = @_;
my @daten;
foreach(keys %foo) {
my @split = split "/", $_;
push @daten, [ @split ];
}
my $tmp_key;
foreach my $data (@daten) {
if(ref $data eq 'ARRAY') {
$tmp_key = "";
my $count = 0;
foreach(@{ $data }) {
$tmp_key .= $_;
$tmp_key .= "/" unless($_ eq $data->[-1]);
$count++;
}
my $max = scalar(@{$data});
my $start = $self->{Hash};
for my $i (1 .. $max) {
my $key = $data->[$i-1];
my $val = $i == $max ? $foo{$tmp_key} : { };
$start = _prepareOrSet($start, $key, $val);
}
}
}
}
sub _prepareOrSet {
my ($href, $key, $val) = @_;
$href->{$key} = $val unless defined $href->{$key};
return $href->{$key};
}
sub getValue {
my $self = shift;
return $self->{Hash};
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
use strict;
use warnings;
use Data::Dumper ();
my $S = {};
sub splitTo {
my ($pH, $pA, $leaf) = @_;
$pA = [ grep $_, split /\//, $pA ] unless ref $pA;
return $leaf unless @$pA;
my $nxt = shift @$pA;
my $pHN = ref $pH->{$nxt} ? $pH->{$nxt} : {};
$pH->{$nxt} = splitTo($pHN, $pA, $leaf);
$pH;
}
splitTo($S, 'foo/bar', 'oops');
splitTo($S, 'foo/bar/baz', '\\o/');
splitTo($S, 'foo/gnu', 'gnat');
print Data::Dumper->Dump([$S], ['S']);
1
2
3
splitTo($S, 'foo/gnu', 'gnat');
splitTo($S, 'foo/bar/baz', '\\o/');
splitTo($S, 'foo/bar', 'oops');
return(keys %$pH ? $pH : $leaf) unless @$pA;
10 Einträge, 1 Seite |