如何将多个 Perl 单行代码合并为一个脚本? [英] How can I consolidate several Perl one-liners into a single script?

查看:98
本文介绍了如何将多个 Perl 单行代码合并为一个脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将多个 one liner 移到一个脚本中.

I would like to move several one liners into a single script.

例如:

perl -i.bak -pE "s/String_ABC/String_XYZ/g" Cities.Txt
perl -i.bak -pE "s/Manhattan/New_England/g" Cities.Txt

以上对我来说效果很好,但代价是两次磁盘 I/O 操作.

Above works well for me but at the expense of two disk I/O operations.

我想将上述逻辑移到单个脚本中,以便所有替换都在文件打开和编辑后仅执行一次.

I would like to move the aforementioned logic into a single script so that all substitutions are effectuated with the file opened and edited only once.

根据您的建议,我在脚本中编写了此代码段,当从 Windows 批处理文件调用时,该代码段只是挂起:

Based on your recommendations, I wrote this snippet in a script which when invoked from a windows batch file simply hangs:

#!/usr/bin/perl -i.bak -p Cities.Txt
use strict;
use warnings;

while( <> ){
s/String_ABC/String_XYZ/g;
s/Manhattan/New_England/g;
print;
}

好的,这就是我实施您的建议的方式.就像魅力一样!

OK, so here is how I implemented your recommendation. Works like a charm!

批处理文件:

perl -i.bal MyScript.pl Cities.Txt

MyScript.pl

#!/usr/bin/perl
use strict;
use warnings;

while( <> ){
s/String_ABC/String_XYZ/g;
s/Manhattan/New_England/g;
print;
}

非常感谢所有做出贡献的人.

Thanks a lot to everyone that contributed.

推荐答案

-p 将参数包裹到 -E 中:

The -p wraps the argument to -E with:

while( <> ) {
    # argument to -E
    print;
    }

所以,把所有的参数带到 -E 并将它们放在 while 中:

So, take all the arguments to -E and put them in the while:

while( <> ) {
    s/String_ABC/String_XYZ/g;
    s/Manhattan/New_England/g;
    print;
    }

-i 设置了 $^I 变量,它开启了一些特殊的魔法处理 ARGV:

The -i sets the $^I variable, which turns on some special magic handling ARGV:

$^I = "bak";

-E 为该版本的 Perl 开启新功能.您只需指定版本即可:

The -E turns on the new features for that versions of Perl. You can do that by just specifying the version:

use v5.10;

但是,您没有使用任何加载了它的东西,至少在您向我们展示的内容中是这样.

However, you don't use anything loaded with that, at least in what you've shown us.

如果您想查看单行程序所做的一切,请输入 -MO=Deparse 在那里:

If you want to see everything a one-liner does, put a -MO=Deparse in there:

% perl -MO=Deparse -i.bak -pE "s/Manhattan/New_England/g" Cities.Txt
BEGIN { $^I = ".bak"; }
BEGIN {
    $^H{'feature_unicode'} = q(1);
    $^H{'feature_say'} = q(1);
    $^H{'feature_state'} = q(1);
    $^H{'feature_switch'} = q(1);
}
LINE: while (defined($_ = <ARGV>)) {
    s/Manhattan/New_England/g;
}
continue {
    die "-p destination: $!\n" unless print $_;
}
-e syntax OK

这篇关于如何将多个 Perl 单行代码合并为一个脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆