Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using system commands in Perl instead of built in libraries/functions [duplicate]

Tags:

scripting

perl

On occasion I see people calling the system grep from Perl (and other scripting languages for that matter) instead of using the built-in language facilities/libraries to parse files. I would like to encourage people to use the built-in facilities and I want to solicit some reasons as to why it is good practice to use the built-in tools. I can think of some such as

  • Using libraries/language facilities is faster. Performance suffers due to the overhead of executing external commands.
  • Sticking to language facilities is more portable.

any other reasons?

On the other side of the coin, are there ever reasons to favour using system commands instead of the built-in language facilities? On that note, if a Perl script is basically only calling external commands (e.g. custom utilities without libraries), might it be better just to make a shell script of it?

like image 520
Friedrich 'Fred' Clausen Avatar asked Dec 10 '13 13:12

Friedrich 'Fred' Clausen


People also ask

What is system command in Perl?

Perl's system command provides a way to execute a shell command on the underlying platform. For example, if you are running on a Unix platform, the command: system("ls -l") will print a long listing of files to stdout.

What is $@ in Perl?

$@ The Perl syntax error or routine error message from the last eval, do-FILE, or require command. If set, either the compilation failed, or the die function was executed within the code of the eval.

How do I run a perl command?

Using system system($command, @arguments); For example: system("sh", "script.sh", "--help" ); system("sh script.sh --help"); System will execute the $command with @arguments and return to your script when finished. You may check $! for certain errors passed to the OS by the external application.


1 Answers

Actually, when it matters, a specialized tool can be faster.

The real gains of keeping the work in Perl are:

  • Portability (even between machines with the same OS).
  • Ease of error detection.
  • Flexibility in handling of errors.
  • Greater customizability/flexibility.
  • Fewer "moving parts". (Are you sure you correctly escaped everything and setup the environment correctly?)
  • Less expertise needed. (You don't need to know both Perl and the external tools (and their ports) to code and maintain the program.)

On that note, if a Perl script is basically only calling external commands (e.g. custom utilities without libraries), might it be better just to make a shell script of it?

Possibly. You can configure some shells to exit if any program returns an unsuccessful error code. This can make some scripts quite robust. For example, I have a couple of bash scripts featuring the line

trap 'e=$? ; echo "Error." ; exit $e' ERR
like image 193
ikegami Avatar answered Sep 22 '22 11:09

ikegami