LS,
I should have this under 'paste' by now, seeing this apparently needs repeating every
so often.
DO NOT READ ENTIRE FILES INTO ARRAYS UNLESS THERE IS NO OTHER OPTION.
are you realising you are slurping an entire file into memory? ever tried that with an
apache log file?
In this case, slurping the file into an array is absolutely and totally pointless.
First you read an entire file into an array
then you loop over all the fields in the array.
why did we need an array for that?
There are a myriad of other options you can use to achieve what you attempt in below
code.
Here are a few:
1. use a *WHILE* loop... it's what they are for.
open I, "input" or die $!
open O, ">output" or die $!
while(<I>) {
s/foo/bar/;
print O;
}
close I;
close O;
2. stringify the entire file.
it's not an ideal thing to do, but a lot less costly then using an array
the use of an array ALSO means requiring a few bits per element to maintain an
index of the array.
something you're not using at all here either.
anyway, how to stringify:
open I, "input" or die $!
open O, ">output" or die $!
my $in;
{ local $/; $in = <I> }
$in =~ s/foo/bar/g;
print O $in;
close I;
close O;
some general points:
you tell the person to 'go away and study regular expressions'
may i advice you to 'go away and study good programming praxis'?
1. check return status of operations.
you don't check the return status of open. - bad -
the file may not be there, it may be locked... you wouldn't know
2. use strict and warnings
you don't use my'd variables (or 'use strict' for that matter) - also bad -
also, run perl under -w, it will tell you when you are doing ambiguous things
3. think
you are choosing probably a very ( if not the most ) inefficient way of
solving this problem
if the file read in is around the size of the available RAM, the machine will
run out of memory.
needless to say, that's bad too.
This email sounds probably a lot ruder than was intended.
no offence is meant, but try and be curteous to people asking questions and help them,
rather then being smug.
and if you're coming up with solutions, please make sure they adhere to 'sensible
programming praxis'
</rant>
Regards,
Jos Boumans
"Walnut" <[EMAIL PROTECTED]> wrote in message
[EMAIL PROTECTED]">news:[EMAIL PROTECTED]...
> #open and read
> open(FILE, "<$filename");
>
> @alllinesinthefile = <>;
>
> close(FILE);
>
> #open and write. Append uses >>
> open(FILE, ">$filename");
>
> print FILE @alllinesinthefile;
>
> close(FILE);
>
> #looping
> foreach $line ( @alllinesinthefile ) {
>
> #Do whatever you want
> # Go away and study regular expressions
> # e.g. $line =~ s/ABC/DEF/g; #substitutes ABC with DEF
> }