in reply to Find a specific word in a text file

If you are going to analyze character by character, you probably want the whole file in one string and to find just the offset of your word. The first part is called slurping the file; one method is to set $/ to undef (see perlvar), then read the file with <> or readline; this will read the whole file. If you then match in scalar context using the g flag, the pos of the string will be set to the end of your match. You can then examine nearby characters with substr. I'd provide an example, but it's not clear exactly what you are going to do once you find a match.
  • Comment on Re: Find a specific word in a text file

Replies are listed 'Best First'.
Re^2: Find a specific word in a text file
by algonquin (Sexton) on Sep 09, 2004 at 10:13 UTC
    Thanks a lot. I now can locate and get the position index of the word I was searching. Now I need to move some blank spaces and 4 letters forward to grab five digits. How do I do that, where can I find an example? Thanks.
      Easiest way is to (adjust pos($yourstring) if needed and) do a scalar match with the //g or //gc flags. Untested:
      # find word if ($string =~ /\bword\b/g) { # skip forward from end of word 12 characters (just an example) pos($string) = pos($string)+12; # skip forward over whitespace and grab 5 digits: if ($string =~ /\s*(\d{5})/gc) { print "here are your digits: $1"; # now pos points to after digits } else { # pos is unchanged (due to /c flag); try something else } }
        Thanks for your help. I got it working now.