On Mon, 2 Sep 2002, Tim Booher wrote:

> Hello, I am currently frustrated trying to do a simple find and replace
> on a file, but the three open options: Read, Write and Append don't seem
> to give me what I want. For example, Read, works on the finding, but
> nothing will replace. Write erases all the files and leaves me with
> blank files and append adds to the end.
>  
> I tried something like:
>  
> open(MYFILE,'+<',$myfile);
>  
> and that didn't work. If you are interested here is my code:
> .. . .
> open(HTMFILE,'+<', $filename) or die "Can't Open: $!";            # now
> go through all .htm files and make changes
>                   while (<HTMFILE>) {
>                         $_ =~ s/leftmargin="0".*bgcolor="#3c3939"//g;
>                         $_ =~ s/bgcolor="\#5A5D4E"/class="topOfPic"/ig;

You are modifying the line that you have read in, but you are not writing 
it back. You will have to open a temporary file write the modified 
contents to it and copy it back to original file for a find and replace.

There are other ways to this, for e.g. using $^I (perldoc perlvar)
Here is an e.g. where I find and replace 'abcd' with 'efgh' in the file 
'test.txt'. Actually perl internally renames the original file, opens a 
new file with the name of the original file to do the processing. In 
effect it is pretty much the same.

my $myfile = 'test.txt';
{
  local @ARGV = ($myfile);
  local $^I = '~'; # perldoc perlvar, 
  # perldoc perlrun, read through section explaining the -i switch
  
  while (<>) { # perldoc perlsyn
    s/abcd/efgh/g;
    print;
  }
}

The same can also be done as an oneliner
perl -i~ -pe 's/abcd/efgh/g' test.txt

You can use any one of these methods for your job.

Note: For HTML parsing you might also want to take look at modules that 
might do this for you. http://search.cpan.org

>                   }
>                   close(HTMFILE);
>                   . . .
>  


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

Reply via email to