Monday, April 27, 2009

Perl array exec() and system() function

exec(PROGRAM);
$result = system(PROGRAM);
Both Perl's exec() function and system() function execute a system shell command. The big difference is that system() creates a fork process and waits to see if the command succeeds or fails - returning a value. exec() does not return anything, it simply executes the command. Neither of these commands should be used to capture the output of a system call. If your goal is to capture output, you should use the backtick operator:
$result = `PROGRAM`;

4 comments:

Anonymous said...

hi, i'm searching on the internet about programming with perl and then found your blog.

i still dont know how to execute a program, then capture the output?

ex: i have a what_time program, it returns the system time value.
Then how do i get the return value of this program?
like: $result = `what_time`;

thanks in advance for your reply and help :)

chorny said...

IPC::System::Simple is very convenient for running other programs from Perl.

me, myself & mbek said...

sorry late reply..

here sample code how to capture output from system call.

my $result = `perl what_time.pl`;
my @results = split(/\n/,$result);
foreach(@results){
print "$_\n";
}

me, myself & mbek said...

my $result = `perl what_time.pl`;

can be change to whatever ur command line is.

at ur case can be change to

my $result = `what_time`;