[英]Using perl's `system`
我想使用perl的system()
運行一些命令(例如command
system()
。 假設從shell運行command
,如下所示:
command --arg1=arg1 --arg2=arg2 -arg3 -arg4
如何使用system()
運行帶有這些參數的command
?
最佳實踐:避免使用shell,使用自動錯誤處理 - IPC::System::Simple
。
require IPC::System::Simple;
use autodie qw(:all);
system qw(command --arg1=arg1 --arg2=arg2 -arg3 -arg4);
use IPC::System::Simple qw(runx);
runx [0], qw(command --arg1=arg1 --arg2=arg2 -arg3 -arg4);
# ↑ list of allowed EXIT_VALs, see documentation
編輯:接下來是咆哮。
eugene y的答案包括系統文檔的鏈接。 在那里,我們可以看到每次都需要包含的一段代碼,以便正確地進行system
處理。 eugene y的答案顯示了其中的一部分。
每當我們處於這種情況時,我們就會在模塊中捆綁重復的代碼。 我使用Try::Tiny
繪制了與正確的簡單異常處理的相似之處,但是IPC::System::Simple
作為system
完成的權利沒有看到社區的這種快速采用。 似乎需要更頻繁地重復。
所以, 使用autodie
! 使用IPC::System::Simple
! 保存自己的單調乏味,請放心使用經過測試的代碼。
my @args = qw(command --arg1=arg1 --arg2=arg2 -arg3 -arg4);
system(@args) == 0 or die "system @args failed: $?";
更多信息是perldoc 。
與Perl中的所有內容一樣,有多種方法可以做到:)
最好的方法,將參數作為列表傳遞:
system("command", "--arg1=arg1","--arg2=arg2","-arg3","-arg4");
雖然有時程序似乎不適合該版本(特別是如果它們希望從shell調用)。 如果您將它作為單個字符串執行,Perl將從shell調用該命令。
system("command --arg1=arg1 --arg2=arg2 -arg3 -arg4");
但那種形式比較慢。
my @args = ( "command", "--arg1=arg1", "--arg2=arg2", "-arg3", "-arg4" );
system(@args);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.