G'day...
Hello,
^^^^^^^^^^^^^^^^On Wed, 2004-11-24 at 23:10, FlashMX wrote:
To be able to do a grep on a file via a perl script do you have to
read the whole file in before performing the search and replace?
I've been hearing that reading the whole file in takes up memory and if multiple users are running the script then you better
have alot of swap and memory.
Is this correct?
Yes and No... You can read a whole file in and perform changes, and then write out the differences to the same filename...
This may or may not take up much memory... a 23K file is only 23K after all... it all depends on your averages...
If this is the case how else could I do a grep to do a search and replace without using all the resources?
You can also read a file in a line at a time, perform the search and
replace on each line, and write the output to a new file... then at the end replace the old file with the new one...
E.g.
open (INFILE, "< $filename"); open (OUTFILE, "> $filename.$$");
You should *always* verify that the files were opened correctly.
open INFILE, '<', $filename or die "Cannot open $filename: $!"; open OUTFILE, '>', "$filename.$$" or die "Cannot open $filename.$$: $!";
for my $line (<INFILE>) {
You imply above that you will read the file "a line at a time" however using a for loop will read the whole file into a list in memory. You need to use a while loop to read a line at a time.
while ( my $line = <INFILE> ) {
$line =~ s/old/new/gi; print OUTFILE $line; }
close(OUTFILE); close(INFILE);
rename("$filename.$$","$filename");
You should verify that rename worked correctly
rename "$filename.$$", $filename or die "Cannot rename $filename.$$: $!";
John -- use Perl; program fulfillment
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>