Why do I lose output when calling another perl program with backquotes

143 Views Asked by At

If I run a perl program and call another perl program using backquotes, print statements from the called program don't appear at the terminal.

If I call the program using 'system', the print statements are displayed.

EG: This is ProgA.pl

print "In ProgA.pl, about to call ProgB.pl";
my $dum=`ProgB.pl`;                       # print output doesn't appear
### $dum=system("ProgB.pl");              # this prints OK
print"\nBack in ProgA.pl";
print "\ndum = $dum";             # ProgB's output doesn't show here either

(No warnings or errors, perl.exe found through file association)

This is ProgB.pl:

print "\nPrinting from ProgB.pl";

What is the reason for the difference?

Why isn't the backquoted call output returned in $dum (I tried both STDOUT and STDERR)? If I call dir in backquotes, I get its output in $dum.

2

There are 2 best solutions below

3
Dave Sherohman On

You have a path issue.

It works as expected ($dum is assigned the value "Printing from ProgB.pl") if I change the backticks from ProgB.pl to ./ProgB.pl. Without the explicit ./ path, it searches the system path and generates an error, as you can see if you change that line to

my $dum=`ProgB.pl` or die $!;

Which generates the output

In ProgA.pl, about to call ProgB.plNo such file or directory at ./ProgA.pl line 4.

Thus illustrating once again that you should always check the return values of your system calls for error conditions.

2
user1067305 On

It appears that by failing to put a newline character at the end of the print command in ProgB, I failed to flush the buffer before returning to ProgA. Thanks to Chris Turner.