in reply to Reading from a file

just dave:

If you're going to look for multiple lines in the file, perhaps you should read the file as one huge string, then use regular expressions to find the lines of interest. For example:

#!/usr/bin/perl -w use strict; use warnings; # Slurp entire file into $file my $file; open FH, $0 or die $!; { # localize scope as described in perlvar local $/; $file = <FH>; } my $line = '---not found---'; $line=$1 if $file=~/\n(ope[^\n]*)/; print "Line='", $line, "'";
should print:

Line='open FH, $0 or die $!;'
--roboticus

Replies are listed 'Best First'.
Re^2: Reading from a file
by just dave (Acolyte) on May 23, 2006 at 12:24 UTC
    roboticus,
    Thanks, but as I've shown in my 1st posting, what I'm doing now, is to read the file into an array and then I can read from the array line-by-line, I don't see how your sugestion is different.
    The main problem is that I read this file a lot(I actually have various reporter files), and I need to find a specific line ( the "header" ) and the last line(the updated "data" )
    my question is: is there a simple way to do so, and is there a way to do so without "saving" the whole file into an array or string or such.
    Thanks
      Sounds to me like Joost had the right idea: Try File::Tail. That would allow you to read the whole file in at startup, scan it for the last header line, and then just pick up the new lines (data or header) as they're added instead of repeatedly reading and processing the entire file.
      just dave:

      I was thinking that by using a single string rather than an array, you can avoid the explicit looping, making your code clearer. Since you also mentioned having a memory leak, I thought that a single string would fragment memory much less than a bazillion smaller strings. That might make it easier for perl to reuse the memory and/or recognize what can be freed

      Other than that, it's not much different at all.

      Of course, since you're rereading the same file repeatedly, I think that Joost's suggestion is my favorite so far. Then, while looking up File::Tail, I saw File::Tail::App, which is pretty cool because it does much of the grunt work for you.

      --roboticus