baxy77bax has asked for the wisdom of the Perl Monks concerning the following question:

hi, my question is; how to make a loop which would search the file from the previous search results and to iterate that loop as long as it goes. example : my problem is that i have a table that looks something like this: x => y, 23 | 32, 12 | 45, 12 | 35, 12 | 67, 45 | 34, 34 | 90, 34 | 55, 35 | 53, 35 | 44, 44 | 41, ... (coma represents new row) now i'm having problems with creating a loop that would find for example #12, return the result(s) for #12 and start the search again with that result(s) (example: 12=>35, 35=>44, 44=>41...). and that it writes down the results of each search. thank you , robert

Replies are listed 'Best First'.
Re: research the search
by moritz (Cardinal) on Aug 27, 2007 at 14:34 UTC
    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.