System ("linux_command") versus Perl library functions

In Perl, you can either use the built-in Perl, or use system (), which calls the shell command to achieve a specific goal. The problem is that for me, as a Perl beginner, it is sometimes difficult to find the Perl equivalent for the Linux command.
Take this for example:

cat file1 file2 | sort -u > file3 

I really want to use only Perl functions to make my Perlish more, but I cannot easily find out how to avoid using system () in this case.

So, I wonder if there is an advantage to using the Perl library functions than using the system () call? Which one is better?

+7
linux perl
source share
5 answers

Often the advantage of using library functions is that you can give meaningful error messages when something goes wrong.

For short-lived scenarios or when development resources are at a high level, using the system may make sense.

+11
source share
 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{$_}++, <>; 

The main advantage is portability and lack of 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; } 
+9
source share

Use the perl library. Saves processor effort when creating another process. You can also get a better indication when things go wrong.

+4
source share

If you want to execute a system command and make it perlish, I recommend using open ().

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

It simplifies and simplifies your program. The support provided by perl for system commands is one of its beauties. So it's best to use it the way it happens, and then go through the whole round of the trip to make your code 'Perlish'.

+1
source share

Of course you can use the Perl script version specified by mpapec . But using the system or open version specified by Asif Idris has some advantages. For example, if you need to sort a large amount of data, using the sort system command will result in a much greater reduction in pain. Sorting multiple GBs using perl is PITA, but it doesn't really matter for the sort system command, and you will even use all your kernels and much less memory.

+1
source share

All Articles