John R
John R

Reputation: 3026

Something like exec() to return a value in Perl?

I am under the impression (perhaps wrongly) that the 'exec' function in Perl does not return a value (I get the impression it just runs the command). The situation is that a Perl script is running on a server and I need to invoke this script to run commands inside the Linux box, but also return the results. How can this be done?

Upvotes: 1

Views: 4610

Answers (6)

vol7ron
vol7ron

Reputation: 42109

Capture STDOUT:

my $dir = `pwd`;
my $dir = qx/pwd/;

Capture Return Status:

my $rc = system('pwd');

Perldocs Capture STDERR and STDOUT:

my $output = `cmd 2>&1`;

See the link for other ways to capture one, output stream, but not the other

Upvotes: 1

TLP
TLP

Reputation: 67900

If by "return the results" you mean return STDOUT of the commands, what you need is backticks or qx(). E.g.:

my $result = qx(echo foo);
# or
my $result2 = `echo foo`;

Do note that messages to STDERR are not returned.

If you mean the exit status of the program, use system:

my $status = system("echo foo");
# or
my $status2 = system("/bin/echo", "foo", "bar");

Upvotes: 8

tadmc
tadmc

Reputation: 3744

Not only does exec() not return a value, it does not return at all.

perldoc -f exec

The exec function executes a system command and never returns use system instead of exec if you want it to return.

But I'm pretty sure that you do NOT want the return value of system(), you seem to want the output of the command, so:

perldoc -f system

This is not what you want to use to capture the output from a command, for that you should use merely backticks or qx//, as described in perlop/"STRING".

Upvotes: 3

FailedDev
FailedDev

Reputation: 26930

From the documentation : http://perldoc.perl.org/functions/system.html

I generally use this :

if(system(@args) != 0)
{
if ($? == -1) {
        print "failed to execute: $!\n";
    }
    elsif ($? & 127) {
        printf "child died with signal %d, %s coredump\n",
            ($? & 127),  ($? & 128) ? 'with' : 'without';
    }
    else {
        printf "child exited with value %d\n", $? >> 8;
    }
}

Upvotes: 2

ObscureRobot
ObscureRobot

Reputation: 7336

The usual perl way to run a program and save its results is backticks:

my $foo = `ls`;

Upvotes: 2

zellio
zellio

Reputation: 32484

using the back-tic

my $var = `shell command`;

in perl allows you to execute shell commands and it returns whatever the output was.

Upvotes: 0

Related Questions