[英]How to execute Perl one liner inside Perl script
I want to execute below one liner in Perl script, to match a line with the values of variables owner
and type
and delete it from the file: 我想在Perl脚本中执行以下划线,以使一行与变量
owner
的值匹配,然后type
并从文件中删除它:
perl -i -ne\"print unless /\b${owner}\b/ and /\b${type}\b/;\" /tmp/test
Content of /tmp/test
: /tmp/test
:
node01 A 10.10.10.2
node02 A 10.20.30.1
This works perfectly fine when I execute in shell, but the same does not work in a Perl script. 当我在shell中执行时,这工作得很好,但是在Perl脚本中却不起作用。
I have tried to use backticks, system
and exec
. 我试图使用反引号,
system
和exec
。 Nothing seems to work. 似乎没有任何作用。
`perl -i -ne\"print unless /\b${owner}\b/ and /\b${type}\b/;\" /tmp/test`
system(q(perl -i -ne\"print unless /\b${owner}\b/ and /\b${type}\b/;\" /tmp/test));
Is it possible to execute Perl one liners inside a Perl script? 是否可以在Perl脚本中执行Perl一个衬板?
If so, what am I doing wrong here? 如果是这样,我在这里做错了什么?
Note: I don't need solution to delete a line from a file with sed, grep, awk etc. 注意:我不需要使用sed,grep,awk等从文件中删除行的解决方案。
You wouldn't want to generate Perl code from the shell, so you'd use one of the following from the shell: 您不想从shell生成Perl代码,因此可以在shell中使用以下之一:
perl -i -ne'
BEGIN { $owner = shift; $type = shift; }
print unless /\b\Q$owner\E\b/ and /\b\Q$type\E\b/;
' "$owner" "$type" /tmp/test
or 要么
ARG_OWNER="$owner" ARG_TYPE="$type" perl -i -ne'
print unless /\b\Q$ENV{ARG_OWNER}\E\b/ and /\b\Q$ENV{ARG_TYPE}\E\b/;
' /tmp/test
The Perl equivalents are Perl的等效项是
system('perl',
'-i',
'-n',
'-e' => '
BEGIN { $owner = shift; $type = shift; }
print unless /\b${owner}\b/ and /\b${type}\b/;
',
$owner,
$type,
'/tmp/test',
);
and 和
local $ENV{ARG_OWNER} = $owner;
local $ENV{ARG_TYPE} = $type;
system('perl',
'-i',
'-n',
'-e' => 'print unless /\b\Q$ENV{ARG_OWNER}\E\b/ and /\b\Q$ENV{ARG_TYPE}\E\b/;',
'/tmp/test',
);
Rather than calling a one-liner, you could emulate the -i
and -n
flags. 您可以模拟
-i
和-n
标志,而不是单线调用。 -n
just requires a while loop. -n
只需要一个while循环。 -i
involves creating and writing to a temporary file and then renaming it to the input file. -i
涉及创建和写入临时文件,然后将其重命名为输入文件。
To choose the temporary filename, you could use /tmp/scriptname.$$
which appends the processId to a basename of your choice. 要选择临时文件名,可以使用
/tmp/scriptname.$$
,它将processId附加到您选择的基本名称之后。 A more sophisticated solution could use File::Temp . 更复杂的解决方案可以使用File :: Temp 。
open(IN, "<$file") || die "Could not open file $file";
open(OUT, ">$out") || die "Could not create temporary file $out";
while(<IN>) {
print OUT $_ unless /\b$owner\b/ and /\b$type\b/;
}
close(IN);
close(OUT) || die "Could not close temporary file $out";
rename($out, $file) || die "Failed to overwrite $file";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.