I'd consider that bad use of a global variable. Whether you
are using OO or not. There are perfectly valid uses for globals,
but to pass data in and out of functions isn't one of them.
A few things to consider:
- What if during you query an exception is thrown? Then
everything that catches an exception has to take care
of cleaning up the global.
- What if you have a more complex operation, and a query
might actually do another query on the tree? With a global,
your algorithm wouldn't be "re-entrant".
There's no good reason to want to use a global here, it's
trivial in Perl to combine lists. Just use recursion and
return a list of answers. Here's an example for doing a range
query on an ordered binary tree:
sub range_query {
my ($node, $from, $to) = @_;
return () unless $node;
return range_query ($node -> left, $from, $to) if $to < $node -
+> key;
return range_query ($node -> right, $from, $to) if $from > $node -
+> key;
return range_query ($node -> left, $from, $to), $node -> key,
range_query ($node -> right, $from, $to)
}
Abigail