從例子學(xué)習(xí)Perl的system函數(shù)

從例子學(xué)習(xí)Perl的system函數(shù)

例子1

避免:
system("chown $user.sgd newdata.txt");
推薦:
system("/usr/bin/chown $user:sgd newdata.txt");
system("/usr/ucb/chown $user.sgd newdata.txt");

理由:如果不是絕對路徑,那么不同的用戶執(zhí)行腳本的時候,由于環(huán)境不一樣,命令可能不一樣。此外,由于沒有指定絕對路徑,會有安全隱患。

例子2

避免:
if (!system("$sub_script $user $file")) {
    print "success!\n";
}
推薦:
if (system("$sub_script $user $file") == 0) {
    print "success!\n";
}

理由:system函數(shù)的返回值低8位存Unix Signal,高位存命令執(zhí)行的返回值,因此,如果需要判斷shell命令是否執(zhí)行成功,必須判斷返回的值是否為0.

例子3

避免:
system("rm $dir/orf_geneontology.tmp");
system "mkdir $tempDir";
system("/bin/kill -HUP $pid");
推薦:
unlink("$dir/orf_geneontology.tmp");
mkdir $tempDir;
$number_killed = kill('HUP', $pid);

理由:盡量使用Perl內(nèi)置的函數(shù)。

例子4

推薦:
open(PS, "/usr/bin/ps -aux |");
while (<PS>) { print } # process the output of ps command one line at a time
close(PS);
This is generally preferable to creating a temporary file with the output and reading it back in:
避免:
my $temporary_file = "/tmp/ps_output$$";
system("/usr/bin/ps -aux > $temporary_file");
open(PS, $temporary_file);
while (<PS>) { print } # process the output of ps command one line at a time
close(PS);
unlink($temporary_file);

理由:第一種寫法更加簡潔,更加Perl!

exec函數(shù)從來不返回(相當(dāng)于重新執(zhí)行了一個新的程序),因此很少使用。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,923評論 18 139
  • //Clojure入門教程: Clojure – Functional Programming for the J...
    葡萄喃喃囈語閱讀 3,766評論 0 7
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,765評論 18 399
  • 轉(zhuǎn)眼間來到內(nèi)科大已經(jīng)快兩個月了,我也從一名滿懷壯志的高中生變成了一名大一新生,這期間雖然飽嘗了山重水復(fù)疑無...
    1aa6688a2d81閱讀 623評論 0 0
  • 高階函數(shù)英文叫Higher-order function。那么什么是高階函數(shù)?在數(shù)學(xué)和計(jì)算機(jī)科學(xué)中,高階函數(shù)是至少...
    JackWhite閱讀 914評論 0 1