rsennat has asked for the wisdom of the Perl Monks concerning the following question:

hi all,

how to store the output of a system call to a variable??
something shown below like this,
$results[0]{result} = system "./script1.pl"; $results[1]{result} = system "./script2.pl";
thanks
rsennat

Replies are listed 'Best First'.
Re: how to store the output of a 'system' call to a variable
by Limbic~Region (Chancellor) on Jan 04, 2006 at 08:01 UTC
    rsennat,
    It sounds like you want to use backticks or qx.
    my $result = `./script.pl`;
    If on the other hand, you actually want to be using the STDOUT of the script - then see answer above.

    Cheers - L~R

Re: how to store the output of a 'system' call to a variable
by serf (Chaplain) on Jan 04, 2006 at 10:53 UTC
    If you are wanting to run a command specifically to capture its output and it gives more than a few lines you may find this way works well for you:
    my $script = "./script1.pl"; open(SCRIPT1, "$script|") || die "Can't run '$script': $!\n"; while(<SCRIPT1>) { $results[0]{result} .= $_; } close(SCRIPT1);
    or perhaps more flexibly:
    my $script = "./script1.pl"; my @script_output; open(SCRIPT1, "$script|") || die "Can't run '$script': $!\n"; while(<SCRIPT1>) { chomp(); push (@script_output, $_); } close(SCRIPT1); $results[0]{result} = join($/, @script_output);
    Both of which will report to you if there is a problem running it (with the reason why) and will put the output which you require into the variable you want to use.
Re: how to store the output of a 'system' call to a variable
by tirwhan (Abbot) on Jan 04, 2006 at 07:48 UTC

    Any particular reason why you're not using backticks or IPC::Open3 for this?


    A computer is a state machine. Threads are for people who can't program state machines. -- Alan Cox
Re: how to store the output of a 'system' call to a variable
by vennirajan (Friar) on Jan 04, 2006 at 09:02 UTC
    Hi,

         You can use backtick operator.Example:
    my $result = `./script.pl`;

         But dont rely on this backtick operator or 'system' functions. Because of two reasons,

  • They will not give us the error messages. To get them, we need to explicitly redirect them. Example,
     my $result = `./script.pl 2>&1`;
  • Next, if you go for this OS depended functions, your code needs change for another OS to get the same functionality. Instead of this we can go for the builtin functions which is available in perl itself.

    Regards,
    S.Venni Rajan.
    "A Flair For Excellence."
                    -- BK Systems.
A reply falls below the community's threshold of quality. You may see it by logging in.