在Perl中,可以使用Perl内置或使用system()调用shell命令来实现某个目标.问题是,对于我作为Perl初学者,有时很难找到与Linux命令相当的Perl.
以此为例:
cat file1 file2 | sort -u > file3
Run Code Online (Sandbox Code Playgroud)
我真的只想使用Perl函数来制作更多的Perlish,但我不能轻易找到如何在这种情况下避免使用system().
所以我想知道,使用Perl库函数比使用system()调用有什么好处吗?哪种方式更好?
local $^I;
local @ARGV = qw(file1 file2);
open my $fh, ">", "file3" or die $!;
my %s;
# print {$fh} (LIST) # or using foreach:
print $fh $_ for
sort
grep !$s{$_}++,
<>;
Run Code Online (Sandbox Code Playgroud)
主要优点是可移植性,没有系统依赖性.
更明确的版本,
use List::MoreUtils qw(uniq);
local $^I;
local @ARGV = qw(file1 file2);
open my $fh, ">", "file3" or die $!;
for my $line (sort uniq readline()) {
print $fh $line;
}
Run Code Online (Sandbox Code Playgroud)