從例子學(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í)行了一個新的程序),因此很少使用。