Thread rekursive subroutine (11 answers)
Opened by kimmy at 2014-02-06 14:52

hlubenow
 2014-02-06 21:54
#173441 #173441
User since
2009-02-22
875 Artikel
BenutzerIn
[default_avatar]
Ich schätze mal, Du willst voll auflösen. Das sähe bei mir so aus:
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/perl

use warnings;
use strict;

sub get_arr {
    my $key = shift;
    my $href = shift;
    my %h = %{$href};
    my @arr = ();
    foreach my $i (@{$h{$key}}) {
        if (exists($h{$i})) {
            push(@arr, &get_arr($i, $href));
        } else {
            push(@arr, $i);
        }
    }
    return @arr;
}

sub getHashRefFromData {
    my @d = <DATA>;
    my %h = ();
    foreach my $i (@d) {
        chomp($i);
        my @a = split(": ", $i);
        my @b = split(", ", $a[1]);
        $h{$a[0]} = [];
        foreach my $u (@b) {
            push(@{$h{$a[0]}}, $u);
        }
    }
    return \%h;
}

my $h = &getHashRefFromData();

for (my $i=1; $i<=9; $i++) {
    my $a = "[$i]";
    print "$a\t";
    my @res = &get_arr($a, $h);
    my $x = 0;
    foreach my $u (@res) {
        print "$u";
        if ($x < $#res){
            print ", ";
        }
        $x++;
    }
    print "\n";
}

__DATA__
[1]: a, b
[2]: c, [1]
[3]: d, e
[4]: f, [3]
[5]: g, h
[6]: i, [5]
[7]: [2], [4]
[8]: j, [6]
[9]: [7], [8]

Edit: Wenn man die Sache mit "__DATA__" wegläßt, kann man sich eine Funktion sparen, und es wird nochmal kürzer:
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
#!/usr/bin/perl

use warnings;
use strict;

sub get_arr {
    my $key = shift;
    my %h = ("[1]" => ["a", "b"],
             "[2]" => ["c", "[1]"],
             "[3]" => ["d", "e"],
             "[4]" => ["f", "[3]"],
             "[5]" => ["g", "h"],
             "[6]" => ["i", "[5]"],
             "[7]" => ["[2]", "[4]"],
             "[8]" => ["j", "[6]"],
             "[9]" => ["[7]", "[8]"]);
    my @arr = ();
    foreach my $i (@{$h{$key}}) {
        if (exists($h{$i})) {
            push(@arr, &get_arr($i));
        } else {
            push(@arr, $i);
        }
    }
    return @arr;
}

for (my $i=1; $i<=9; $i++) {
    my $a = "[$i]";
    print "$a\t";
    my @res = &get_arr($a);
    foreach my $u (0 .. $#res) {
        print "$res[$u]";
        if ($u < $#res){
            print ", ";
        }
    }
    print "\n";
}

Zugegeben, "get_arr()" ist nicht der schönste Name ... ;)
Last edited: 2014-02-06 22:22:54 +0100 (CET)

View full thread rekursive subroutine