regex - Perl: search for a match multiple times in a file -


in perl script, opened file , search string. successful. when search same string again right after search, seems script starts searching until end of file, , hence not able find match more. code like:

open ( infile, "./input.txt")  for($i=0; $i < 3; $i++){      print "i = $i\n";     $found = 0;      while (! $found && ($line = <infile>)){         if ( $line =~ /string/ ){            print "found!\n";            $found = 1;         }         else{            print "not found!\n";         }     } }  close (infile); 

the input.txt file:

string random2 random2 

i expecting output be:

i = 0 found! = 1 found! = 2  found! 

but turns out be:

i = 0 found! = 1 not found! not found! = 2 

can me this. started learning perl.

you're getting because when read file in perl mark last position read in file won't read again, in case read whole file marked end of file , need reset position doing seek beginning again

for($i=0; $i < 3; $i++ ){     seek(infile,0,0);     #... 

this reset filehandle start again see perl seek tut

since you're starting learning perl here's general instructions may use

  • always use strict

  • use three-argument form of open

    open ( $infile, "<", "./input.txt"); 
  • use my every variable localization


Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -