in reply to Newbie Text Parsing Question

Yes and yes.

If the files are small, the easiest way to "back up" is to read the whole thing into memory. Something like this:

# Loop over all files with a .log suffix foreach my $fn (<*.log>) { # Open the file, if possible, and read it all into @f open I, $fn or warn("Couldn't open $fn: $!"), next; my @f = <I>; close I; # Go through it a line at a time for (my $i = 0; $i < @f; $i++) { # If you find "hello" anywhere in the line, # Back up two lines and print if possible if ($f[$i] =~ /hello/) { print $f[$i-2] if $i > 1; print $f[$i-1] if $i > 0; print $f[$i]; } # Note, if you don't care about "undefined value" # warnings, print the three elements without any # condition. } }
If the files are large, this could eat up lots of memory. In that case, you'll have to play games with backing up inside the file, which is trickier. (An exercise for the reader. ;-)

HTH

Replies are listed 'Best First'.
Re: Re: Newbie Text Parsing Question
by kanikilu (Initiate) on Jul 06, 2001 at 00:26 UTC
    Thanks for the reply! The files should be between about 5 and 45 KB. Is this too big? I'll try what you suggested and reply back...
      Thanks! It worked perfectly. I added a couple lines to output it to a file and make the output a little "prettier", but it suits my purposes just fine. And there doesn't seem to be any memory 'issues'... Thanks again.