Perl in place edit within a script

perlregex

I need to edit a file in place within a perl script, so the oft used one liner:

perl -p -e s/<value>/<value>/ig 

will not work for this situation. How do I get the same results from within a perl script?

open(CRONTAB, "+<file" || die "...";

while (<CRONTAB>) { 
   if ($_ =~ /value/) {  
      s/^\#+//;  
      print "$_\n";  
   }  
}

My print is showing exactly what I want. It's just the in place edit that I'm looking for.

Best Answer

do {
  local $^I='.bak'; # see perlvar(1)
  local @ARGV=("file");
  while(<>){
    s/<value>/<value>/ig;
    print;
  }
};

Beware though: $^I like perl's -i isn't crashproof.

Related Topic