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

Hi Monks,

I have to run a perl script within a main script. I want the standard output of the called perl script to be written in a variable defined within the calling script.

I have tried using this construct:

$my = `/home/hey/abc.pl`;

This is not working. Any suggestions.

Thanks

  • Comment on Directing STDOUT of called perl script to a variable within a calling perl script
  • Download Code

Replies are listed 'Best First'.
Re: Directing STDOUT of called perl script to a variable within a calling perl script
by toolic (Bishop) on Jul 03, 2012 at 13:50 UTC
    Are you sure abc.pl is generating output when called outside the script? Is it to STDOUT or STDERR? You can check for errors (Tip #7 from Basic debugging checklist):
    $my = `/home/hey/abc.pl`; print $? if $?;
Re: Directing STDOUT of called perl script to a variable within a calling perl script
by zentara (Cardinal) on Jul 03, 2012 at 13:48 UTC
    This is not working

    What is abc.pl supposed to do? Why do you think it is not working? Backticks would be the number 1 answer to your question, but you say it dosn't work. Read perldoc -q capture and come back with more information.

    Just as a wag, try

    $my = `/home/hey/abc.pl` or die "something wrong $!\n";
    Quite possibly your permissions are wrong on the script, or it dosn't have a shebang line.

    I'm not really a human, but I play one on earth.
    Old Perl Programmer Haiku ................... flash japh
Re: Directing STDOUT of called perl script to a variable within a calling perl script
by NetWallah (Canon) on Jul 03, 2012 at 14:49 UTC
    There is a possibility that the script does not get executed, for a number of reasons - no ".pl" association, executable permissions, bad path, missing shbang etc.

    1. Try adding "perl" or "/usr/bin/perl" in front.
    2. Try adding "2>&1" at the end - maybe STDERR has something while STDOUT does not.
    3. Check for errors as suggested above.

                 I hope life isn't a big joke, because I don't get it.
                       -SNL

Re: Directing STDOUT of called perl script to a variable within a calling perl script
by Khen1950fx (Canon) on Jul 04, 2012 at 01:48 UTC
    IPC::System::Simple would be a good way to handle this.
    #!/usr/bin/perl use strict; use warnings; use IPC::System::Simple qw/capturex/; my $cap = capturex("perl", "/root/Desktop/abc.pl"); die "Couldn't capture output: $!" unless $cap; print $cap;