• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Replacing text in a file using perl script

 
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

I need to replace some value in config file using perl script. I used this code -


When i print $file , it shows me the changed rows but it does not write it to a file. Please suggest.

Regards,
Patricia samuel
 
Ranch Hand
Posts: 781
Netbeans IDE Ubuntu Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Since your are reading the whole file into memory you can safely re-open the file and write to it i.e.


 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I just learnt, much to my surprise, that the following code works too:

foreach $line (@lines)
{  
   $line =~ s/hello/hello hello hello/ig;  
}
print OUT @lines;
close OUT;

I had no idea that changing $line in the for loop actually changed the @lines array.
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

James Sabre wrote:Since your are reading the whole file into memory you can safely re-open the file and write to it i.e.



I would NEVER write the changed lines out to the same file.  Odds are too great that you screw something up, and your original file is lost forever.  I'd always write the output to a new temp file, inspect it to be sure it is correct, and then rename the original as a .old or some such.
 
Saloon Keeper
Posts: 27762
196
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Perl has a command-line option for this. It makes the change "in place", but also produces a back-up copy of the original file.

This is invaluable, since I almost never get the changes right on the first try!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic