3

In the unix/linux version, I'd simply change the first line:

#!perl -i.bak

Using Activestate perl on windows, where I've created the association with .pl, I can run a perl script directly from the command line.

myScript.pl

How can I do inplace editing of files if I still want to use the default association?

chris
  • 36,094
  • 53
  • 157
  • 237

2 Answers2

5

Sounds like a trick question, and I wonder if I am understanding you right.

perl -pi.bak myScript.pl myfiletochange

Just call perl, supply the switches and the script name, and off you go.

Now, it may be that you do not want to supply these extra arguments. If so, you can simply set the variable $^I, which will activate the inplace edit. E.g.:

$^I = ".bak"; # will set backup extension
TLP
  • 66,756
  • 10
  • 92
  • 149
  • No trick - creating a script for a non-technical user, and would like to have it self-contained. Thanks. – chris Mar 28 '12 at 14:08
  • 1
    @chris Your non-technical user should be aware that while the script saves a backup, that backup is overwritten for each subsequent use of the script on the source file. – TLP Mar 28 '12 at 14:47
  • 2
    They all say it's a one-time thing. :) – brian d foy Mar 28 '12 at 18:54
  • @chris It's only a one-time thing until the next time. =P – TLP Mar 28 '12 at 21:15
0

Since you are going to be using a script you might want to do something like this:

sub edit_in_place
{
    my $file       = shift;
    my $code       = shift;
    {
        local @ARGV = ($file);
        local $^I   = '';
        while (<>) {
            &$code;
        }
    }
}

edit_in_place $file, sub {
    s/search/replace/;
    print;
};

if you want to create a backup then change local $^I = ''; to local $^I = '.bak';

DavidGamba
  • 3,503
  • 2
  • 30
  • 46