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

kimmy
 2014-02-06 15:23
#173421 #173421
User since
2010-09-10
87 Artikel
BenutzerIn
[default_avatar]
Das ist mein Code.
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
#!/usr/bin/perl

use strict;
use warnings;

my (%child, @ancestor); 

while(<DATA>){
        my ($node, $left, $right);
        $node = $1, $left = $2, $right = $3 if(/(.+?): (.+?), (.+)/);
        $child{$node} = $left . ' ' . $right;   
        push @ancestor, $node;

        if($left =~ /^\w/ && $right =~ /^\[/){
                my $children_node = child_check($child{$right});
                $child{$node} = $left . ', ' . $children_node;
                # $right wird vom Array @ancestor entfernt
                @ancestor = grep !/^\Q$right\E$/, @ancestor;
        }
}

foreach(@ancestor){
        #my $vater_id = $_;
        my $descendant = $child{$_};
        print "$_:\t$descendant\n";
}

sub child_check{
        my $string = shift;
        my @arr_ance = split(/ /, $string);
        my @all_children;
        foreach my $ance(@arr_ance){
                if (defined $child{$ance}) {
                        my @descendants = split(/ /, $child{$ance});
                        foreach my $desc(@descendants){
                                if (defined $child{$desc}) {
                                        child_check($child{$desc});
                                }
                                else{
                                        push @all_children, $desc;
                                }
                        }               
                }
                else{
                        push @all_children, $string;
                }       
        }       
        my $join_children = join(', ', @all_children);
        return $join_children;
}

__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]

View full thread rekursive subroutine