Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

system("linux_command") vs. Perl library functions

Tags:

linux

perl

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?

like image 447
duleshi Avatar asked Nov 12 '13 06:11

duleshi


3 Answers

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.

like image 104
ysth Avatar answered Oct 14 '22 03:10

ysth


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;
}
like image 22
mpapec Avatar answered Oct 14 '22 01:10

mpapec


Use perl library. Saves the processor effort in spawning another process. Also able to get better indication when things go wrong.

like image 25
Ed Heal Avatar answered Oct 14 '22 03:10

Ed Heal