2014-05-02 38 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");