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

Fellow Monks, I have written a very short subroutine that executes some system calls. I want to use the values and send them to a formatted file that I have created with the reporting format within Perl, but I am not getting very far. Any help would be appreciated. The below snippet is shown below where I want to get the output from the system calls into the formatted file called FORMATTED. How can I capture the values? It seems to just run the system calls.
print FORMATTED FILE "$SECU\n"; sub _showSecInfo { system ("$SEC","t"); system ("$SEC","s"); };

Replies are listed 'Best First'.
Re: Subroutine Return Values
by Zaxo (Archbishop) on Jan 12, 2007 at 01:07 UTC

    To capture STDOUT of a system call, you want to use backticks ( ` ` ) or the equivalent qx. The system function only gives you the exit status.

    You should be checking for errors in those calls by testing $?.

    After Compline,
    Zaxo

Re: Subroutine Return Values
by siva kumar (Pilgrim) on Jan 12, 2007 at 04:01 UTC
    The 'system' will give you only the exit status not the STDOUT. See below the difference between backticks, system call and exec.
    $var = `ls`; print "\n---\n $var \n---\n "; The $var will have the output of 'ls' command.

    $var = system('ls'); print "\n---\n $var \n---\n ";
    In the above code, ls command will be executed and $var will have the zero value but not the output of the 'ls' command.
    $var = exec('ls'); print "\n---\n $var \n---\n ";
    Here ls command will get executed but $var will have nothing. More, the program will get terminated after exec execution.
    So I guess, you have to use backticks instead of system call.
      This is either a nit, or ignorance, but...

      using AS 5.8.8 (819) on Win XP (gack, but no *n*x allowed at work), the last variant script in siva_kumar 's otherwise well-considered reply HANGS (as the knowledgable may well have expected).

      It appears that his word "program" refers to ls (which was replaced with dir for this win test) but that the statement "Here ls command will get executed but $var will have nothing." would be more precise if rephased to:

      "Here the ls command will be executed, but will never return control to the script. Hence, the line to print $var will never be executed."

      From perldoc perlfunc: The "exec" function executes a system command *and never returns*-- use "system" instead of "exec" if you want it to return.

        Yes I agree. Thanks for comment.