string replace problem

D

diggnet

Helo,

I have a little problem with string replace in HTML file. I want to
replace :

OLD_STRING = "<img width="11" height="11"
src="/include/image-dir/jsp/images/image1.gif">"

NEW_STRING ="image1"

any ideas how to do it with perl?


digg.
 
J

Jürgen Exner

Helo,

I have a little problem with string replace in HTML file. I want to
replace :

OLD_STRING = "<img width="11" height="11"
src="/include/image-dir/jsp/images/image1.gif">"

This won't even compile.
NEW_STRING ="image1"

any ideas how to do it with perl?

Sure.
$OLDSTRING = $NEWSTRING;
should do the job.

Now, what is your real problem?

jue
 
T

Tad McClellan

I want to
replace :

OLD_STRING = "<img width="11" height="11"
src="/include/image-dir/jsp/images/image1.gif">"

NEW_STRING ="image1"

any ideas how to do it with perl?


Here is a program that does that:

--------------------
#!/usr/bin/perl
use warnings;
use strict;

my $old_string = q(<img width="11" height="11"
src="/include/image-dir/jsp/images/image1.gif">);

my $new_string ="image1";

my $html = q(<html><body><img width="11" height="11"
src="/include/image-dir/jsp/images/image1.gif"></body></html>);

$html =~ s/$old_string/$new_string/;

print $html;
 
D

diggnet

hi,

and if i want to change in whole file? where and how shoul i declare
it? in.ex. $infile
 
D

diggnet

Ok... i've made it :

#!/usr/bin/perl
use warnings;
use strict;
my $old_string = q(<img width="11" height="11"
src="/include/image-dir/jsp/images/image1.gif">);
my $new_string ="image1";
my $infile = "infile.html";
my $outfile = "outfile.html";
open(FILE,"< $infile");
open(FILE2,"> $outfile");
while(<FILE>) {
$_=~ s/$old_string/$new_string/g;
print FILE2 "$_";
}
close(FILE2);
close FILE;
 
T

Tad McClellan

open(FILE,"< $infile");


You should always, yes *always*, check the return value from open():

open(FILE,"< $infile") or die "could not open '$infile' $!";

The "best" way to open the file would be to use a lexical filehandle
and the 3-argument form of open():

open(my $FILE, '<', $infile) or die "could not open '$infile' $!";

print FILE2 "$_";


print FILE2 $_;
or
print FILE2;


See: perldoc -q vars

What's wrong with always quoting "$vars"?
 
J

John W. Krahn

Ferry said:
Tad Mc Clellan:


What is the difference between

open (my $FILE, '<', $infile)... and
open (my $FILE, "<$file")... ?

Say you have a file named ' file ', the first case would work correctly but
the second case would ignore the whitespace and try to open the file named 'file'.


John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,188
Messages
2,571,002
Members
47,591
Latest member
WoodrowBut

Latest Threads

Top