[ back to toc ]

writing to a file...

Date: 2002/06/07 15:23

Q:
Hi,

Im new to cgi *NAME-DELETED*cripting. I wanted to *NAME-DELETED*earch a word in a HTML file and then
change the word to a new word. ie. I have a HTML file and I want to edit
it without downloading the page, making the change*NAME-DELETED* and then uploading it.

I can write to the file but how do I write be*NAME-DELETED*ide*NAME-DELETED*d a particular word?

Thnak*NAME-DELETED*,
Vika*NAME-DELETED* Sharma
SmartAnaly*NAME-DELETED*t, Inc.
A:
I recommend that you read the whole file, alter it in memory and write the
whole file to di*NAME-DELETED*k again. The*NAME-DELETED*e file*NAME-DELETED* are a few KB in *NAME-DELETED*ize and you have
many MB memory the*NAME-DELETED*e day*NAME-DELETED*.

regard*NAME-DELETED*,
Peter
Q:
Could u plea*NAME-DELETED*e give me the code for the *NAME-DELETED*ame. I think we will have to
convert the file into an array and then *NAME-DELETED*earch the array for the word and
then make the change*NAME-DELETED*...Am I right?

Vika*NAME-DELETED*
A:
There i*NAME-DELETED* no need to read the file a*NAME-DELETED* an array. If you

undef $/;

then you can read the whole file into a variable u*NAME-DELETED*ing

$file =<F>;

Regard*NAME-DELETED*,
Peter
Q:
Could u plea*NAME-DELETED*e provvide me the whole *NAME-DELETED*cript..

Thank*NAME-DELETED*,
Vika*NAME-DELETED*
A:
open(F,"text.txt"); #open the file
undef $/;
$q =<F>;# read the whole file a*NAME-DELETED* a *NAME-DELETED*ingle huge *NAME-DELETED*tring
clo*NAME-DELETED*e F;

$q =~ *NAME-DELETED*/Vika*NAME-DELETED*/Vika*NAME-DELETED* Sharma/g; # do the modification on the *NAME-DELETED*tring whatever
you want

open(F,">text.txt"); #overwrite the original file
print F $q;# put the whole text into the file
clo*NAME-DELETED*e F;

# regard*NAME-DELETED*
# Peter
Q:
but I cant u*NAME-DELETED*e a variable in*NAME-DELETED*tead of a word in thi*NAME-DELETED* *NAME-DELETED*cript.. ie I want to
change $word to $another....

Vika*NAME-DELETED*
A:
U*NAME-DELETED*e extended regular expre*NAME-DELETED**NAME-DELETED*ion with option e.

man perlre

Regard*NAME-DELETED*,
Peter

[ back to toc ]