duleshi
duleshi

Reputation: 2024

system("linux_command") vs. Perl library functions

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?

Upvotes: 7

Views: 326

Answers (5)

mpapec
mpapec

Reputation: 50657

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;
}

Upvotes: 9

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26121

You can of course use Perl script version as pointed out by mpapec. But usage of system or open version pointed by Asif Idris have some advantages. For example if you need sort big amount of data, using system command sort will bring you much further wit a lot less pain. Sorting few GB using perl is PITA but it is not big deal for system command sort and you will even use all your cores and much less memory.

Upvotes: 1

Asif Idris
Asif Idris

Reputation: 21

If you want to execute a system command and making it perlish i will recommend using open().

open(fh,"cat test.txt text_file.txt | sort -u >new_file.txt | ");

This makes your program simple and easy to understand.The support provided in perl for system commands is one of the beauties of it.So its better to use it the way it is rather then going the whole trip round just to make your code 'Perlish'.

Upvotes: 1

Ed Heal
Ed Heal

Reputation: 60017

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

Upvotes: 4

ysth
ysth

Reputation: 98398

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.

Upvotes: 11

Related Questions