What you'll want to do is read
Mastering Algorithms With Perl by Jon Orwant et al.
Then indeed you'll be able to do what you want to do.
At the risk of giving away information too easily (and thus
reducing the likelihood of enlightenment), here's an untested,
off-the-top-of-my-head example of doing linked lists
in Perl:
A linked list node is just a data structure with one slot
for data and one slot pointing to another node. So you could
use an anonymous array, like so:
##
## make_node()
## Arguments: $value: scalar, contents of the node
## $next_node: linked list node (optional)
##
sub new_node {
my ($value, $next_node) = @_;
my $new_node = [$value, $next_node];
return $new_node;
}
Okay, okay, so that would build the node backwards, but hey.
Then, you could build an entire list by doing this:
$last_node = new_node('last', undef);
$middle_node = new_node('middle', $last_node);
$first_node = new_node('first', $middle_node);
You could traverse this list like so:
sub traverse_nodes
{
my ($node) = @_;
my ($value, $next_node) = @$node;
if ( defined($next_node) ) {
return ($value, traverse_nodes($next_node));
}
else {
return $value;
}
}
At least I think that'll work. Somebody speak up if
I'm smoking something. Then:
print join(' ', traverse_nodes($first_node) ), "\n";
should print "first, middle, last".
stephen
|