Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call a shell command in my Perl script?

Tags:

perl

What would be an example of how I can call a shell command, say 'ls -a' in a Perl script and the way to retrieve the output of the command as well?

like image 921
Yang Avatar asked Jul 08 '10 05:07

Yang


People also ask

How do I open a command prompt in Perl?

my $cmd = "perl -w otherscript.pl"; my $result = system( "start /LOW $cmd" ); This should start the desired command in a new window and return immediately.


2 Answers

How to run a shell script from a Perl program

1. 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. Read the documentation for system for the nuances of how various invocations are slightly different.

2. Using exec

This is very similar to the use of system, but it will terminate your script upon execution. Again, read the documentation for exec for more.

3. Using backticks or qx//

my $output = `script.sh --option`;  my $output = qx/script.sh --option/; 

The backtick operator and it's equivalent qx//, excute the command and options inside the operator and return that commands output to STDOUT when it finishes.

There are also ways to run external applications through creative use of open, but this is advanced use; read the documentation for more.

like image 66
fire.eagle Avatar answered Sep 21 '22 06:09

fire.eagle


From Perl HowTo, the most common ways to execute external commands from Perl are:

  • my $files = `ls -la` — captures the output of the command in $files
  • system "touch ~/foo" — if you don't want to capture the command's output
  • exec "vim ~/foo" — if you don't want to return to the script after executing the command
  • open(my $file, '|-', "grep foo"); print $file "foo\nbar" — if you want to pipe input into the command
like image 45
sjy Avatar answered Sep 24 '22 06:09

sjy