Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between system, exec, and backticks in Perl?

Tags:

perl

ipc

In Perl, to run another Perl script from my script, or to run any system commands like mv, cp, pkgadd, pkgrm, pkginfo, rpm etc, we can use the following:

  • system()
  • exec()
  • `` (Backticks)

Are all the three the same, or are they different? Do all the three give the same result in every case? Are they used in different scenarios, like to call a Perl program we have to use system() and for others we have to use ``(backticks).

Please advise, as I am currently using system() for all the calls.

like image 436
PJ. Avatar asked Sep 04 '09 04:09

PJ.


3 Answers

They're all different, and the docs explain how they're different. Backticks capture and return output; system returns an exit status, and exec never returns at all if it's successful.

like image 107
hobbs Avatar answered Oct 12 '22 13:10

hobbs


IPC::System::Simple is probably what you want.

It provides safe, portable alternatives to backticks, system() and other IPC commands.

It also allows you to avoid the shell for most of said commands, which can be helpful in some circumstances.

like image 6
aaa90210 Avatar answered Oct 12 '22 15:10

aaa90210


The best option is to use some module, either in the standard library or from CPAN, that does the job for you. It's going to be more portable, and possibly even faster for quick tasks (no forking to the system).

However, if that's not good enough for you, you can use one of those three, and no, they are not the same. Read the perldoc pages on system(), exec(), and backticks to see the difference.

like image 3
Chris Lutz Avatar answered Oct 12 '22 15:10

Chris Lutz