If what you're doing is fork-friendly (i.e. doesn't involve modifying global variables), Perl has a built-in syntax just for you -- with open. (This sort of thing, by the way, is why I occasionally reread the perl PODs.)
#foo() is the sub that outputs a lot of data
my $pid = open(SUBOUT, '-|');
defined($pid) or die "Fork failed: $!";
if ($pid == 0) {
$|=1; foo(); exit(0);
}
while (<SUBOUT>) ...
The open will fork your script, and the forked copy (the one that calls the function) will have its STDOUT piped to the filehandle given to open() (in this case, SUBOUT).
Here's a quick example I crafted:
#!/usr/bin/perl -l
defined($tmp = open(FOO, '-|')) or die "Can't fork: $!";
if ($tmp==0) {
print "Roses are red\nViolets are blue\nI think Perl rules\nAn
+d you should too\n";
exit(1);
}
print for map {chomp; "[$tmp] {$_}"} <FOO>;
--Stevie-O
$"=$,,$_=q>|\p4<6 8p<M/_|<('=>
.q>.<4-KI<l|2$<6%s!<qn#F<>;$,
.=pack'N*',"@{[unpack'C*',$_]
}"for split/</;$_=$,,y[A-Z a-z]
{}cd;print lc
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|