replacing text

They have: 314 posts

Joined: Nov 1999

hey,

I'm going to be making a script which takes the user input and adds it to a .shtml file for inclusing in another page. I want the latest input put at the top and so thought that I could make it write the input to the file in this format:

userinput for Q 1
user input for Q 2
etc etc

Now when the script writes to the file I want it to replace with the new input (in the format above). This would mean that there is always the thing to be replaced with the new input.

My question is what is the code to replace something with something else?

Cheers

They have: 850 posts

Joined: Jul 1999

Try using the following:


$file = 'C:\windows\desktop\data.txt';
{
local $/;
open(IN,$file) or die "Cannot open $file to read: $!";
$html = <IN>;
close(IN);
}
$html =~ s/<TOP>/<TOP>\n$newinput<br>/;

open(IN,">$file") or die "Cannot open $file to write: $!";
print IN $html;
close(IN);
'

To search/replace use a regular expression like above
$variable =~ s/SEARCH FOR/REPLACE WITH/g;
the g modifier is optional, what it does is look more than once through a file to find what you are searching for. But considering there is only one in your file, it is not required.

Hope that helps.

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

your gonna want to parse the user input for
if they put that in their input, there will be instances of

$file = 'C:\windows\desktop\data.txt';
{
local $/;
open(IN,$file) or die "Cannot open $file to read: $!";
$html = <IN>;
close(IN);
}
$newinput = /<TOP>/&lt;TOP&gt;/g;
$html =~ s/<TOP>/<TOP>\n$newinput<br>/;

open(IN,">$file") or die "Cannot open $file to write: $!";
print IN $html;
close(IN);
'

Mark Hensler
If there is no answer on Google, then there is no question.

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.