1 |
williamc |
1.1 |
#
|
2 |
|
|
# TreeMonkey - Climb around the tree as directed by a search string
|
3 |
|
|
#
|
4 |
|
|
# Interface
|
5 |
|
|
# -----------
|
6 |
|
|
# new() : A new monkey is born
|
7 |
|
|
# find(string) : Tell the monkey to search the tree for the node at the
|
8 |
|
|
# location indicated by the string, relative to the current
|
9 |
|
|
# tree node.
|
10 |
|
|
# goto(TreeNode) : Tell the monkey to go to a particular node in the tree
|
11 |
|
|
|
12 |
|
|
package TreeMonkey;
|
13 |
|
|
|
14 |
|
|
sub new {
|
15 |
|
|
my $class=shift;
|
16 |
|
|
$self={};
|
17 |
|
|
bless $self, $class;
|
18 |
|
|
return $self;
|
19 |
|
|
}
|
20 |
|
|
|
21 |
|
|
sub goto {
|
22 |
|
|
my $self=shift;
|
23 |
|
|
$self->{currentnode)=shift;
|
24 |
|
|
}
|
25 |
|
|
|
26 |
|
|
sub find {
|
27 |
|
|
my $self=shift;
|
28 |
|
|
my $string=shift;
|
29 |
|
|
my @words;
|
30 |
|
|
my $first;
|
31 |
|
|
my $found=0;
|
32 |
|
|
|
33 |
|
|
# Split string
|
34 |
|
|
($first, @words)=split '/', $string;
|
35 |
|
|
|
36 |
|
|
# Search towards root for first word or until we reach root
|
37 |
|
|
while ( ( $self->{currentnode}->name() ne $first ) ||
|
38 |
|
|
( $self->{currentnode)->parent() ne "" ) ) {
|
39 |
|
|
$self->{currentnode)=$self->{currentnode)->parent();
|
40 |
|
|
}
|
41 |
|
|
|
42 |
|
|
# Check the case of just a single word
|
43 |
|
|
if (( $#words == 0 ) && ( $self->{currentnode}->name() eq $first )) {
|
44 |
|
|
$found=1;
|
45 |
|
|
}
|
46 |
|
|
|
47 |
|
|
# Now Search the child branches for the pattern
|
48 |
|
|
my $n=0;
|
49 |
|
|
my $i=0;
|
50 |
|
|
while ( $found==0 && $n>=0 ) {
|
51 |
|
|
$children=$self->{currentnode}->listbranch()) {
|
52 |
|
|
$n=$#children;
|
53 |
|
|
$branch=$children[$n]
|
54 |
|
|
if ( $branch eq $words[$i] ) {
|
55 |
|
|
$self->{currentnode}=$branch;
|
56 |
|
|
$i++;
|
57 |
|
|
if ( $n > $#words ) { $found=1; }
|
58 |
|
|
}
|
59 |
|
|
else {
|
60 |
|
|
$n--;
|
61 |
|
|
}
|
62 |
|
|
} # end while
|
63 |
|
|
|
64 |
|
|
# Now return the object ID of the found node or null
|
65 |
|
|
if ( $found==1 ) {
|
66 |
|
|
return $self->{currentnode};
|
67 |
|
|
}
|
68 |
|
|
else {
|
69 |
|
|
return "";
|
70 |
|
|
}
|
71 |
|
|
}
|