简体   繁体   English

在Perl脚本中执行Unix命令

[英]Execute Unix command in a Perl script

How I can make the following external command within ticks work with variables instead? 如何在刻度内使以下外部命令可代替变量工作?

Or something similar? 还是类似的东西?

sed -i.bak -e '10,16d;17d' $docname ; sed -i.bak -e '10,16d;17d' $docname ; (this works) (这有效)

Ie, sed -i.bak -e '$line_number,$line_end_number;$last_line' $docname ; sed -i.bak -e '$line_number,$line_end_number;$last_line' $docname ;

my $result = 
      qx/sed -i.bak -e "$line_number,${line_end_number}d;${last_line}d" $docname/;

Where the line split avoid the horizontal scroll-bar on SO; 行拆分时,避免在SO上使用水平滚动条; otherwise, it would be on one line. 否则,它将在一行上。

Or, since it is not clear that there's any output to capture: 或者,由于尚不清楚是否需要捕获任何输出,因此:

system "sed -i.back '$line_number,${line_end_number}d;${last_line}d' $docname";

Or you could split that up into arguments yourself: 或者您可以自己将其分解为参数:

system "sed", "-i.back", "$line_number,${line_end_number}d;${last_line}d", "$docname";

This tends to be safer since the shell doesn't get a chance to interfere with the interpretation of the arguments. 因为外壳程序没有机会干扰参数的解释,所以这往往更安全。

@args = ("command", "arg1", "arg2");
system(@args) == 0 or die "system @args failed: $?"

Furthermore on the manual: 此外,在手册上:

perldoc -f system

I think you should read up on using qq for strings. 我认为您应该阅读有关使用qq作为字符串的内容。

You probably want something like this: 您可能想要这样的东西:

use strict;
use warnings;

my     $line_number = qq|10|;
my $line_end_number = qq|16d|;
my       $last_line = qq|17d|;
my        $doc_name = qq|somefile.bak|;
my     $sed_command = qq|sed -i.bak -e '$line_number,$line_end_number;$last_line' $doc_name;|;

print $sed_command;
qx|$sed_command|;

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

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