You should store the pairs in a hash.
You are not very specific about what to do when multiple values are present, here is an implementation that visits all siblings that can be visited from one parent (you are representing a tree, right?)
#!/usr/bin/perl
use strict;
use warnings;
my %chain;
# read the chain:
while (<DATA>){
chomp;
my ($key, $val) = split m/ \| /;
push @{$chain{$key}}, $val;
}
# walk the chain starting from 12:
walk(12);
sub walk {
my $c = shift;
print "Visiting $c\n";
for (@{$chain{$c}}){
walk($_);
}
}
__DATA__
23 | 32
12 | 45
12 | 35
12 | 67
45 | 34
34 | 90
34 | 55
35 | 53
35 | 44
44 | 41
And the corresponding output:
Visiting 12
Visiting 45
Visiting 34
Visiting 90
Visiting 55
Visiting 35
Visiting 53
Visiting 44
Visiting 41
Visiting 67
Update: If you have cycles in your chain this will loop forever. If you do, you have to mark the pairs that you have used in the traversal, and never use a pair twice.
|