Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

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 = "www.3sat.de/boerse/boerse_service.html"; my $replace = "there.company.com/"; $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
http://www.horus.com/~bjelli/         http://perlwelt.horus.at


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

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (14)
As of 2015-07-03 12:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (53 votes), past polls