2014-05-02 114 views
3

我遇到了单引号导致系统调用中Bash'未端接引号字符串'错误的情况。在这个特定的情况下,我试图将$DBI::errstr插入到bash命令中。我正在使用系统调用:反斜杠在Perl中的单引号

system "echo '$DBI::errstr' | mail -s 'error' [email protected]"; 

因此$DBI::errstr有时包含单引号并导致错误。我知道我可以将$DBI::errstr放在反斜杠的双引号\"$DBI::errstr\"中,并称它为一天,但是必须有更好的方式来处理带有正则表达式的引号或者编写一个子例程,这是我找不到的。我也试过quotemeta,但是这也会反过来削减空间。

+1

[字符串:: ShellQuote](https://metacpan.org/pod/String::ShellQuote)? – tobyink

+0

您也可以切换到[Mail :: Sender](http://p3rl.org/Mail::Sender),因此您不必引用任何内容。 – choroba

+0

'$ DBI :: errstr'的​​值是什么?它里面有单引号吗? – Oktalist

回答

4

没有很好的理由在Perl使用system echo。你可以简单地打开一个管道作为文件句柄并打印到它:

open my $mail, '|-', qw/mail -s error [email protected]/ or die $!; 
print $mail $DBI::errstr, "\n"; 

编辑:但要回答你的问题更笼统。与其依赖shell来解析和取消引用命令行字符串并将其转换为参数,通常使用system()的显式多参数形式更好。因此,您可以使用system("some_command", "--arg=$val")而不是system "some_command --arg=$val",并担心是否需要为shell引用$val

+0

打开管道非常适合我的情况,并且我确信system()的多参数形式在不久的将来会非常有用+1 – BryanK

+0

+1可以很流畅地回答。但'qw/mail -s error [email protected] /'会更好;任何'死亡'都应该有*作为参数,特别是'$!',如果它是适当的,就像它在这里 – Borodin

+0

@Borodin,责备@ikegami为'邮件','-s','错误' ,'usr @ mail.com''语法。好点关于$ !.现在修复。 – tetromino

2

如果你要使用system,这是你会怎么做:

use String::ShellQuote qw(shell_quote); 

my $cmd1 = shell_quote('echo', $DBI::errstr); 
my $cmd2 = shell_quote('mail', '-s', 'error', $email_addr); 
system("$cmd1 | $cmd2"); 
相关问题