Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://105801]
[karlgoethebier]: hi marto
[karlgoethebier]: hi all
[marto]: hey karlgoethebier

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (6)
As of 2017-12-13 12:30 GMT
Find Nodes?
    Voting Booth?
    What programming language do you hate the most?

    Results (364 votes). Check out past polls.