preahkumpii
preahkumpii

Reputation: 1301

Perl: While loop will not continue with specified variables

Here is my code:

while (<LIST>) {
    if (m|^\w|) {
        chomp;
        print "$_\n";
    }
    if (m|^\t|) {
        chomp;
        $search = substr($_, 1);
        print "  $search\n";
        while (<BIBLE>) {
            while ($_ =~ /\b$search\b/ig) {
                $book = substr($_, 0, 2);
                $chap = substr($_, 3, 3);
                $verse = substr($_, 7, 3);
                print "      $book:$chap:$verse\n";
            }
        }
    }
}

So, basically, I have a word list and a corpus. I am taking words from lines that only begin with tabs and making those words my search terms. Then, I am wanting to search the BIBLE file handle to find every occurrence of that search term. It works as expected UNTIL the second main loop. It is entering the loop to print the remaining words in the list, but not reassigning the $search variable and doing a search in the corpus again for each word successively. Here is the output:

headword1
  abahandiiki
      41:001:022
      41:002:016
      41:003:022
      41:007:005
      41:008:031
      41:009:011
      41:009:014
      41:009:016
      41:010:033
      41:011:018
      41:011:027
      41:012:035
      41:012:038
      41:014:001
      41:014:043
      41:014:053
      41:015:001
      41:015:031
      43:008:003
  abahe
  abaheereza
headword2
  baheereza
  baheerezakazi
  bahiire
  bahikiirire
  bahingi
  bahungire
headword3
  okurikuhikiirizibwa
  okurikushushana
  okurikusiimwa
  okurikwera
  okurogota
  okuruga
  okurugirira
  okurungi
  okurwanisa
  okurya
  okushaagaana
  okushara

Any ideas on how to make the subsequent searches work? Is there something wrong with the code?

Upvotes: 1

Views: 188

Answers (1)

Bill Ruppert
Bill Ruppert

Reputation: 9026

This program is trying to read the entire BIBLE file for each word in the list. The file is being consumed by the first word, and then going EOF for each word after that. You need to close and reopen the BIBLE file for each word. Of course, this is a spectacularly bad way of doing this. Check out Lingua::Condordance in CPAN.

Or as Mat says, you can just do a seek(BIBLE, 0, 0);

Upvotes: 2

Related Questions