1

I'm trying to modify a script that someone else has written and I wanted to keep my script separate from his.

The script I wrote ends with a print line that outputs all relevant data separated by spaces.

Ex: print "$sap $stuff $more_stuff";

I want to use this data in the middle of another perl script and I'm not sure if it's possible using a system call to the script I wrote.

Ex: system("./sap_calc.pl $id"); #obtain printed data from sap_calc.pl here

Can this be done? If not, how should I go about this?


Somewhat related, but not using system():

How can I get one Perl script to see variables in another Perl script?

How can I pass arguments from one Perl script to another?

Community
  • 1
  • 1
CheeseConQueso
  • 5,831
  • 29
  • 93
  • 126
  • 2
    read the documentation for the function you are using! "perldoc -f system" answers your question in the 3rd paragraph "what you want to use to capture the output from a command, for that you should use merely..." – tadmc Dec 20 '11 at 18:35

3 Answers3

5

You're looking for the "backtick operator."

Have a look at perlop, Section "Quote-like operators".

Generally, capturing a program's output goes like this:

my $output = `/bin/cmd ...`;

Mind that the backtick operator captures STDOUT only. So in order to capture everything (STDERR, too) the commands needs to be appended with the usual shell redirection "2>&1".

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
4

If you want to use the data printed to stdout from the other script, you'd need to use backticks or qx().

system will only return the return value of the shell command, not the actual output.

Although the proper way to do this would be to import the actual code into your other script, by building a module, or simply by using do.

As a general rule, it is better to use all perl solutions, than relying on system/shell as a way of "simplifying".

myfile.pl:

sub foo {
    print "Foo";
}
1;

main.pl:

do 'myfile.pl';
foo();
TLP
  • 66,756
  • 10
  • 92
  • 149
1

perldoc perlipc

Backquotes, like in shell, will yield the standard output of the command as a string (or array, depending on context). They can more clearly be written as the quote-like qx operator.

@lines = `./sap_calc.pl $id`;
@lines = qx(./sap_calc.pl $id);
$all = `./sap_calc.pl $id`;
$all = qx(./sap_calc.pl $id);

open can also be used for streaming instead of reading into memory all at once (as qx does). This can also bypass the shell, which avoids all sorts of quoting issues.

open my $fh, '-|', './sap_calc.pl', $id;
while (readline $fh) {
    print "read line: $_";
}
ephemient
  • 198,619
  • 38
  • 280
  • 391