简体   繁体   English

如何在Windows上使用Perl进行就地编辑(-i)?

[英]How can I do inplace editing (-i) with perl on windows?

In the unix/linux version, I'd simply change the first line: 在unix / linux版本中,我只需更改第一行:

#!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. 在Windows上使用Activestate perl(我已使用.pl创建了关联),我可以直接从命令行运行perl脚本。

myScript.pl

How can I do inplace editing of files if I still want to use the default association? 如果仍要使用默认关联,该如何对文件进行就地编辑?

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. 只需调用perl,提供开关和脚本名称,就可以开始使用。

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. 如果是这样,您可以简单地设置变量$^I ,这将激活就地编辑。 Eg: 例如:

$^I = ".bak"; # will set backup extension

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 = ''; 如果要创建备份,则更改local $^I = ''; to local $^I = '.bak'; local $^I = '.bak';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM