How to call a shell command in our Perl script

Overview

There are two ways to call a shell command from the Perl script.

Syntax

We use the backticks (``) syntax when we want to capture the output of the shell command. We provide the command between the backticks.

my $variableName = `provide your command here`

If we don't want to capture the output of the shell command, we use the system function, as shown below. The system function will just display the output.

system("provide your command here")

Example

# usage backticks
my $output = `ls -l`;
print "------display the captured output with backticks------ \n";
print $output;
print "\n------display the output of disk usage command with system------- \n";
#usage of system
system("df -h");

Explanation

  • Line 2: We call a shell command from a Perl script, using backticks, and capture the output in a Perl variable output.
  • Line 4: We display the output captured in line 2.
  • Line 8: We call a shell command from the Perl script using the system function. The system function displays the output.

Free Resources