我想知道這裏的最佳做法。假設我想獲取文件某行的內容。我可以使用單行shell命令來獲得我的答案,或者編寫一個子例程,如下面的代碼所示。在Perl腳本中,我們應該使用shell命令還是調用模仿shell操作的Perl函數?
的文本文件命名爲some_text
:
She laughed. Then both continued eating in silence, like strangers,
but after dinner they walked side by side; and there sprang up
between them the light jesting conversation of people who are free
and satisfied, to whom it does not matter where they go or what
they talk about.
代碼來獲取文件
#!perl
use warnings;
use strict;
my $file = "some_text";
my $lnum = 5;
my $shellcmd = "awk 'NR==$lnum' $file";
print qx($shellcmd);
print getSrcLine($file, $lnum);
sub getSrcLine {
my($file, $lnum) = @_;
open FILE, $file or die "$!";
my @ray = <FILE>;
return $ray[$lnum-1];
}
我問這個的第5行的內容,因爲我看到了很多的Perl腳本,其中在某些時候,一個shell命令被調用,而在稍後的某個時間點,通過調用(庫或手寫)函數完成相同的任務,例如rm -rf
與File::Path::rmtree
。我只是想讓它一致。
建議做什麼?
Recomended方式取決於代碼的意圖。如果你想在Non Unix機器上執行,然後去perl庫,否則看看我已發佈的鏈接..希望這有助於.. – Rajeev 2012-04-01 18:44:52
也許每個腳本是在一段時間內開發的,可能是由多個程序員開發的。腳本發展了,代碼不是100%自我一致的,部分取決於那些涉及Perl或shell的經驗有多少。 – 2012-04-01 18:51:56
請注意,雖然汲取整個5行文件以獲得第五行不是太痛苦,但它可能是獲得第五行百萬行文件的次優策略。 – 2012-04-01 18:54:31