我希望了解最佳实践。假设我想获取文件中某一行的内容。我可以使用单行shell命令或编写子程序来获取答案,如下面的代码所示。
名为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.
获取文件第5行内容的代码
#!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];
}
我之所以问这个问题,是因为我看到很多 Perl 脚本,在某些时候调用了 Shell 命令,而在稍后的某个时候,则通过调用(库或手写的)函数来完成相同的任务,例如,
rm -rf
与 File::Path::rmtree
。我只是想让它保持一致。那么,推荐采取什么做法呢?
FILE
变量不是词法作用域(my
)文件句柄,所以退出函数时它不会自动关闭。建议使用open my $FILE, '<', "$file" or die "$!";
和my @ray = <$FILE>;
。这种方法在函数终止时会关闭文件。如果在调用getSrcLine
后添加seek(FILE, 0, 0) or die "$!";
,你可以证明FILE
没有被关闭,因为它不会生成错误。 - Jonathan Leffler