Azubi Cai wrote at Tue, 01 Jul 2003 16:40:23 +0200:

> I need to substitute a string in a .rtf file with a string from an HTML
> form.
> I thought about using placeholders in the .rtf document and then
> searching and overwriting them with the data from the HTML form.
> I tried it out with that code:
> 
> #!/usr/bin/perl -w
> open PASSWD, "test.rtf"
>  or die "nichts gefunden ($!) ";
> 
> while (<PASSWD>) {
> chomp;
> if (/welt/) {
> s/welt/mars/;
>       }
> }

Your program open a file,
read it line by line into a variable,
chomp that variable
and substitute something of that variable.

But a variable per se, don't change the world.
In general you will need another outputfile to write to and finally
you simply move the new file to the old one.

That would look like:

#!/usr/bin/perl

use strict;
use warnings;

open PASSWD, "<test.rtf" or die "Error: $!";
open PASSWD_TMP, ">test.rtf.tmp" or die "Error: $!";

while (<PASSWD>) {
    # chomping doesn't make a lot of sense here,
    # as we won't change the newline

    s/welt/mars/;   # the if condition isn't necessary and is no
                    # optimization

    print PASSWD_TMP;
}

rename "test.rtf.tmp", "test.rtf";

Of course that program still has the known problems when using temporary
files, but it illustrates the main principle.

> there aren't any warn messages from the compiler, but the string "hallo
> welt" hasn't changed into "hallo mars".
> But whats' wrong? Or is it a problem with the .rtf format?

Perl would not be Perl, if it wouldn't make a simple problem simple.
You can replace the whole above program by a simple one liner:

perl -pi -e 's/welt/mars/';

(read perldoc perlrun to understand what -pi and -e does)

Greetings,
Janek

PS: Might be that you want to switch on also the g-modifier:
    s/welt/mars/g
    as without it, you will only change the first welt of every line to
    mars.


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to