1. Perl
  2. Operators
  3. here

Backticks operator - Run another process and get standard output

You can use the backticks operator to run another process and get the standard output produced by that process.

# Backticks operator
my $output = `$cmd`;

It's pretty similar to system function. The system function returns an exit status, while the backticks operator returns the standard output of the process.

Execute the ls command

As an example of the backticks operator, let's execute the Linux ls command that displays the contents of the current directory.

my $output = `ls`;

$output shows a list of current directories.

a.pl gperl module-starter.txt not_important_project ringowiki static-perl.tar
batch Image-PNG-Simple mojo Object-Simple role task deal
crontab.txt imager-japanese-translation.wiki mojo-examples

To check the return value of the calling process

How do you check if the process you call with the backticks operator fails or returns an error status?

Predefined variable Use "$?".

If this value is non-zero, then some error has occurred.

# Error checking
if ($?) {
  die "Command error";
}

You can also know the error status in more detail.

$? Is a 16-bit value, and the exit status of the child process is stored in the upper 8 bits. You can get the exit status by shifting to the right 8 bits.

my $output = `ls`;

# Check the exit status of the child process
my $status = $? >> 8;
if ($status != 0) {
  # Error handling
}

Backticks operator security

The backticks operator is a security-prone operator. For example, suppose the input data from the Web is "rm" and you pass it unchecked to the backticks operator.

The backticks operator executes unintended commands.

If you are receiving input from the user programmatically, make sure that the string you pass to the backticks operator is safe.

Backticks operator example

This is an example backticks operator.

use strict;
use warnings;

my $output = `ls -l`;

if ($?) {
  die "Command error";
}

print "$output\n";

Related Informatrion