【问题标题】:why do I have to pipe perl output into a new perl command为什么我必须将 perl 输出通过管道传输到新的 perl 命令中
【发布时间】:2019-08-17 10:13:47
【问题描述】:

我想在执行许多其他正则表达式替换的 perl 脚本中删除反引号 (\x60) 和单词字符之间的空格。如果我将先前替换的结果打印到 bash shell,然后通过管道传输到新的 perl 调用中,它就可以工作。但是在单个 perl 调用中,它没有。在下面的示例中,第三行(单个 perl 命令)不起作用,而第四行(两个单独的命令)起作用。

printf '%b' 'Well, `\n he said it \n' 
printf '%b' 'Well, `\n he said it \n' | perl -p -e 'use strict; use warnings; s|\n||g;' ; echo
printf '%b' 'Well, `\n he said it \n' | perl -p -e 'use strict; use warnings; s|\n||g; s|([\x60])\s*(\w)|$1$2|g;' ; echo
printf '%b' 'Well, `\n he said it \n' | perl -p -e 'use strict; use warnings; s|\n||g;' | perl -p -e 'use strict; use warnings; s|([\x60])\s*(\w)|$1$2|g;'; echo

为什么它在单个 perl 调用中不起作用?我认为我们应该避免使用多个或嵌套的管道(子外壳)。

这是 BSD unix 中的 perl 5,版本 18 和 GNU bash,版本 3.2.57(1)。

【问题讨论】:

    标签: bash perl recursion pipe string-substitution


    【解决方案1】:

    因为您的perl -p 在换行符上拆分,所以您的第一个 perl 将它们删除,而第二个 perl 将所有内容都视为一行。

    printf '%b' 'Well, `\n he said it \n' | perl -p0 -e 'use strict; use warnings; s|\n||g; s|([\x60])\s*(\w)|$1$2|g;' ; echo
    

    通过告诉 perl 一次全部输入,第一个 s 可以删除新行,第二个将删除引号后的空格。

    【讨论】:

    • -0 实际上并没有启用 slurp 模式;为此使用-0777
    • @Tanktalus,这很有帮助。 -0 和 -0777 记录在哪里?在 perl 脚本而不是命令行调用中,语法如何更改以执行此操作?
    猜你喜欢
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 2012-02-29
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    相关资源
    最近更新 更多