如何在这段Perl代码中进行转义?

3
#!/usr/bin/perl
use warnings;
system ("dialog --menu Customize 10 70 50 'Flush rules' 'Clear all the rules' 'Show rules' 'Shows the current rules' 2> /tmp/tmp.txt ")

我希望以更易读的方式编写上述代码,就像这样:
#!/usr/bin/perl
use warnings;
system ("dialog --menu Customize 10 70 50 
'Flush rules' 'Clear all the rules' 
'Show rules' 'Shows the current rules' 
'more options' '........' 2> /tmp/tmp.txt ")

我该怎么做?

1
你尝试过使用“ .<newline> ”吗?(即将句点作为字符串连接符号)? - transistor1
哎呀!我忘记了。谢谢 :) - Chankey Pathak
如果可以的话,我总是很乐意帮忙! - transistor1
3个回答

5
Perl提供了一个字符串拼接运算符,您可以使用它来构建大字符串:
system ( "dialog --menu Customize 10 70 50 "
       . "'Flush rules' 'Clear all the rules' "
       . "'Show rules' 'Shows the current rules' "
       . "'more options' '........' 2> /tmp/tmp.txt ");

2

system 可以接受 @args(数组形式):

system ( 'dialog', @args );

1
这样做行不通,因为OP正在使用shell元字符,他需要避免绕过shell...所以他需要对system()进行一次单参数调用。 - tadmc
@tadmc:没错——除非他自己在Perl中实现I/O重定向。 - Keith Thompson

1
system ( "dialog --menu Customize 10 70 50 "
   . "'Flush rules' 'Clear all the rules' "
   . "'Show rules' 'Shows the current rules' "
   . "'more options' '........' 2> /tmp/tmp.txt ");

哇,tadmc 真快。是的,请使用 . 连接命令。

我建议您将命令创建在单独的字符串中,然后执行它。我还建议使用 qq 命令来进行引用。这样,您就不必担心单引号和双引号的问题:

my $command = qq(dialog --menu Customize 10 70 50 )
   . qq("Flush rules" 'Clear all the rules' )
   . qq('Show rules' 'Shows the current rules' )
   . qq'more options' '........' 2> /tmp/temp.$$ );

my $error = system $command;

使用qq可以让你不必担心是否需要使用双引号来允许变量插值或单引号,或者必须转义引号。例如,我能够混合使用双引号和单引号,并且可以使用Perl变量而不必担心是否必须从单引号更改为双引号。例如,我使用/tmp/temp.$$。其中的$$是进程ID,因此如果执行此命令两次,则使用两个不同的临时文件。

通过为我的命令创建一个单独的变量,我现在可以稍后使用它--例如,如果我的系统命令出现错误。

顺便说一下,您应该始终检查您的system命令的返回值。如果由于某种原因无法执行系统命令,则很可能要出错或至少注意问题。

其中一个问题是系统命令的输出与大多数Perl函数相反。在大多数Perl函数中,返回零表示失败,而返回非零表示成功。但是,system函数恰好相反。零表示成功,非零表示失败。

这可能会导致奇怪的if结构:

if (system $command) {
    die qq(Can't execute command "$command"\n);
};

这看起来像是我在说,如果我的系统命令成功,我应该死亡,但实际上它的意思与这个相同:

my $error = system $command;

if ($error) {
   die qq(Can't execute command "$command"\n);
}

从语法上讲,这更有意义。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接