Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re: Read from a file and replace

by bjelli (Pilgrim)
on Aug 18, 2001 at 00:18 UTC ( #105801=note: print w/ replies, xml ) Need Help??

in reply to Read from a file and replace

What you want is called "inplace editing" in perl. Here it is, try to spot the difference to your own code:

$^I = ".bak"; @ARGV = ('file.html'); while(<>) { # chomp; # don't want to loose the linebreaks my $string = "$_"; my $find = ""; my $replace = ""; $find = quotemeta $find; $string =~ s/$find/$replace/g; print $string; }

Here's what you do:

  1. Put the list of files you want to treat into @ARGV
  2. Set $^I. For every file treated, the original is saved with $^I added to the filename
  3. read from <>
  4. print to STDOUT

Perl does all the right things: it opens the files in @ARGV one by one, creates backups, and writes your output back into the original files.

P.S. Everything has already been discussed on perlmonks: see modifying and overwriting a file

Brigitte    'I never met a chocolate I didnt like'    Jellinek

Comment on Re: Read from a file and replace
Download Code

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://105801]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (7)
As of 2015-10-08 20:26 GMT
Find Nodes?
    Voting Booth?

    Does Humor Belong in Programming?

    Results (226 votes), past polls