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

Hi, I am havinga few probs with the following code. It would appear that the seond while loop is only cycle once; doesnt go back in the second time.
open (FH, "filtered.txt"); open (IN, "information"); while (<IN>) { chomp $_; /images\/(\d+)/; $sample = $1; print "$sample\n"; while (<FH>){ /(\d+)/; print "loop\n"; } } }

Replies are listed 'Best First'.
Re: loop problem
by davidrw (Prior) on Jun 14, 2005 at 14:24 UTC
    After the first loop, you've already read the whole FM file, so it is at EOF, so on the second, etc pass there's nothing to read. To fix this, either do a seek to the beginning right before the inner while loop, or open/read/close FM entirely within the outer loop.
    BUT, also question whether or not you HAVE to be re-reading FM every time from disk in the inner loop -- can you just dump the whole thing into an array in memory before the outer loop runs? If so, it will be very much faster...
      thanks for those thoughts, the array method appears to be working
Re: loop problem
by tlm (Prior) on Jun 14, 2005 at 14:22 UTC

    It does, but it has nothing to do, since the lines from FH are exhausted. perl won't automatically start reading from the top of the file again. You can open and close the handle within the outer loop, or do as Transient suggests and save the contents from FH into an array, which you can then traverse as often as you want.

    the lowliest monk

Re: loop problem
by Transient (Hermit) on Jun 14, 2005 at 14:20 UTC
    Once you've gone through the first time, you're at the end of the file. Try slurping the FH into an array and using that (if it's not too big).

    You could probably also use some "if"'s around your regexes
      Transient,
      Try slurping the FH into an array and using that (if it's not too big).

      And if it is too big? I would recommend using tell and seek for the general case and only slurping in the specific case (you know for sure it is a sane thing to do).

      Cheers - L~R

Re: loop problem
by Anonymous Monk on Jun 14, 2005 at 14:19 UTC
    open (FH, "filtered.txt"); open (IN, "information"); while (<IN>) { chomp $_; /images\/(\d+)/; $sample = $1; while (<FH>){ /(\d+)/; print "loop\n"; } }
      open (FH, "filtered.txt"); open (IN, "information"); while (<IN>) { chomp $_; /images\/(\d+)/; $sample = $1; while (<FH>){ /(\d+)/; print "loop\n"; } seek( FH, 0, 0 ); }
      -derby