linux poison RSS
linux poison Email

Perl Script: How to execute bash (or other) scripts from within the Perl script

system() executes the command specified. It doesn't capture the output of the command.

system() accepts as argument either a scalar or an array. If the argument is a scalar, system() uses a shell to execute the command ("/bin/sh -c command"); if the argument is an array it executes the command directly, considering the first element of the array as the command name and the remaining array elements as arguments to the command to be executed.

For that reason, it's highly recommended for efficiency and safety reasons (specially if you're running a cgi script) that you use an array to pass arguments to system().

Below is simple perl script which explains the concept of system() function call.

Source: cat system.pl
#!/usr/bin/perl

# This function is passed a list as follows: The first element of the list contains the name of a program to execute, and the other elements are arguments to be passed to the program.

@prog = ("echo", "hello World!");
system (@prog) == 0 || die "system @prog failed: $?";
print " ------------------------------\n";

# here I am calling simple bash interactive script to add any given 2 numbers.
@prog2 = ("bash", "/home/poison/bash/sumcalc.sh");
system (@prog2) ==0 || die "system @prog2 failed: $?";
print " -------------------------------\n";

$command = "date";
system ($command) == 0 || die "system $command failed: $?";

Output: perl system.pl
hello World!
 ------------------------------
Enter the first number:
12
Enter the second number:
12
Output from function sumcalc: 24
 -------------------------------
Fri Oct 12 15:56:53 EDT 2012





0 comments:

Post a Comment

Related Posts with Thumbnails