In Perl, one can either use a Perl builtin or use system() which calls a shell command to achieve the some goal. The problem is, for me as a Perl beginner, it's sometimes difficult to find the Perl equivalent to a Linux command.
Take this one for example:
cat file1 file2 | sort -u > file3
I really want to use only the Perl functions to make my more Perlish, but I can't easily find out how to avoid using system() in this case.
So I wonder, is there any advantage of using Perl Library functions than using the system() call? Which is the better way?
Often the advantage in using library functions is that you can give meaningful error messages when something goes wrong.
For short-lived scripts or when development resources are at a premium, using system instead can make sense.
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{$_}++,
<>;
Main advantage is portability and not having system dependencies.
More explicit version,
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;
}
Use perl library. Saves the processor effort in spawning another process. Also able to get better indication when things go wrong.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With