Pergunta

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?

Foi útil?

Solução

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

Outras dicas

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';

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top