Sometimes there is a need to capture the output from another perl program and display it in your program. Especially when you use Pterl/Tk and want to invoke a perl program to do something, you want to capture the standard output of the other program “in real time.” Here is a way to do it:
program 1 (call it a):
#!/usr/local/bin/perl -w $|=1; #flush the standard output use strict; sub printMsg { foreach (0.. 10) { sleep(1); print "$_\n"; } } printMsg(); #### end of program

program 2
#!/usr/local/bin/perl -w open(FD,"a|"); while (<FD>) { print $_; }
Idea is to use a pipe. Any comments?

Replies are listed 'Best First'.
Re: capturing output from another perl program
by Zaxo (Archbishop) on Aug 21, 2004 at 00:02 UTC

    That's one of my favorite ways to do it. You may want to adopt perl 5.6+ notation for piped open, use a lexical file handle, and keep the child pid,

    { my $cpid = open my $fd, '-|', 'a' or die $!; print while <$fd>; }
    The three-arg form of open is preferred because it separates the open mode from the file name, and it can take modifiers like ':raw' to activate IO layers, remove the need for binmode, etc.

    Your app could have done this with backticks, but not so well.

    After Compline,
    Zaxo

A reply falls below the community's threshold of quality. You may see it by logging in.