Bootstrap FreeKB - Perl (Scripting) - Native operating system command using `backticks` or system
Perl (Scripting) - Native operating system command using `backticks` or system

Updated:   |  Perl (Scripting) articles

There are a few different ways to run a command in perl that is native to the underlying operating system.

  • Using `backticks`
  • Using "system" and "capture"

Using `backticks`

For simple commands that should never return a Standard Error, backticks is totally fine. 

For example, let's say a Perl script is running on a Linux server. The following script is an example of how backticks can be used to run native Linux commands in Perl. Running this Perl script will print the hostname to the console.

#!/usr/bin/perl
use strict;
use warnings;

my $hostname = `hostname`;
print "$hostname\n";

 

Sometimes, it makes sense to store the native operating system command you want to run as a Perl variable. 

my $file = "cat /path/to/example.txt";

 

Then, you can run the command using backticks and pipe native operating system commands.

my $result = `$file | grep Hello`;

 


Using system and capture

For commands that may sometimes return Standard Error, I almost always go with "system" and "capture" because backticks doesn't have a great way to differentiate between Standard Out and Standard Error. 

By default, the Capture::Tiny module is probably not included with your default Perl installation. You can Install the Capture::Tiny module using cpan or Install the Capture::Tiny module using cpanm.

For example, since "some bogus command" is a bogus command, the output will be stored in Standard Error.

#!/usr/bin/perl
use strict;
use warnings;
use Capture::Tiny qw(capture);

my ($stdout, $stderr, $rc) = capture { system "some bogus command" };

chomp $stdout;
chomp $stderr;
chomp $rc;

if ($stdout) {
  print "capture Standard Out   = $stdout \n";
}
if ($stderr) {
  print "capture Standard Error = $stderr \n";
}
if ($rc) {
  print "capture Return Code    = $rc \n";
}

 

Running this script should return the following, where we can see that the output was stored in Standard Error and the Return Code is -1.

~]$ perl testing.pl
capture Standard Error = Can't exec "some bogus command": No such file or directory at testing.pl line 10. 
capture Return Code    = -1

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 5989f4 in the box below so that we can be sure you are a human.