[英]Perl one liner inside a perl script not working
my text file contents 我的文本文件内容
vi /root/text.conf
node.session.auth.authmethod = hello
so my one liner perl command replaces the above file contents by commenting with #. 因此,我的一个线性perl命令通过用#注释替换了上面的文件内容。 Works fine when run as single command 作为单个命令运行时工作正常
perl -pi -e 's/^(node.session.auth.authmethod\s*=\s*).*$/#\1hello/g' /root/text.conf
when the perl one liner code is executed inside perl script, it does not comment out the text.conf file contents. 当在perl脚本中执行perl一个线性代码时,它不会注释掉text.conf文件的内容。
$cmd ="perl -pi -e 's/^(node.session.auth.authmethod\s*=\s*).*$/#\1hello/g' /root/text.conf"
$line = `$cmd 2>&1`;$ret = $?;
Am I missing something while executing Perl one liner inside a Perl script. 我在Perl脚本中执行Perl一个内衬时是否缺少某些东西?
Yes, use current perl process instead of forking new one. 是的,使用当前的perl进程而不是派生新的进程。 This is equivalent of your 这相当于你的
perl -pi -e 's/^(node.session.auth.authmethod\s*=\s*).*$/#\1hello/g' /root/text.conf
one-liner, 一个内胆,
use strict;
use warnings;
local $^I = "";
local @ARGV = "/root/text.conf";
while (<>) {
s/^(node.session.auth.authmethod\s*=\s*).*$/#\1hello/g;
print;
}
Defining your $cmd
the Variable $/
will be replaced by it's value (the line separator). 定义$cmd
变量$/
将替换为其值(行分隔符)。 Then the regex will not match your line. 然后正则表达式将不匹配您的行。
Try using single quotes (along with proper escaping): 尝试使用单引号(以及正确的转义):
$cmd ='perl -pi -e \'s/^(node.session.auth.authmethod\s*=\s*).*$/#\1hello/g\' /root/text.conf'
$line = `$cmd 2>&1`;$ret = $?;
This will prevent perl from expanding variables. 这将防止perl扩展变量。
Nevertheless mpapec's answer is right, why forking a new process? 尽管如此,mpapec的回答是正确的,为什么要分叉一个新的过程?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.