View Full Version : Perl, Pipes, and PHP's POpen, oh my!
gwfran
02-16-2007, 07:04 AM
I'm having a heck of a time trying to translate php's popen command to something that I can use in Perl (in both Win32 and Unix environs).
function filterThroughCmd($input, $commandLine) {
$pipe = popen("echo \"$input\"|$commandLine" , 'r');
if (!$pipe) {
print "pipe failed.";
return "";
}
$output = '';
while(!feof($pipe)) {
$output .= fread($pipe, 1024);
}
pclose($pipe);
return $output;
}
Where $input is a significant chunk of text (with newlines) being pushed into the command "matchmol.exe -".
It's a challenge... :thumbsup:
ralph l mayo
02-16-2007, 03:22 PM
I haven't used this, but it seems to work:
sub filterThroughCmd
{
my ($input, $cmd) = @_;
open FILTER, "|$cmd" or die $!;
print FILTER $input;
my @resp = <FILTER>;
close FILTER;
return wantarray? @resp : join @resp, "\n";
}
print filterThroughCmd("just\na\ntest", 'wc -l');
gwfran
02-17-2007, 06:18 AM
Thanks Ralph - I'm going to try it right now!!!!!! :thumbsup:
gwfran
02-17-2007, 07:27 AM
Holy cow - the problem was that I was getting CRCRLF's from Perl!!!
A simple regex cured that.
As I step through the code, the open FILTER and print FILTER work great. The results of these two lines are immediately printed to the screen. For some reason @resp = <FILTER> is not catching the results and storing them.
Any ideas?
FishMonger
02-17-2007, 05:07 PM
Please show us the code that you're testing.
FishMonger
02-17-2007, 05:13 PM
Have you tried using backticks to retrieve the output of your external program?
@resp = `echo $input | $commandLine`;
FishMonger
02-17-2007, 05:21 PM
If you want to use the more verbose approach, this should work.
sub filterThroughCmd
{
my ($input, $cmd) = @_;
open FILTER, "| echo $input | $cmd" or die $!;
my @resp = <FILTER>;
close FILTER;
return @resp;
}
gwfran
02-17-2007, 07:04 PM
Thanks Fishmonger.
The code I'm testing is what Ralph provided.
I've tried the backtick and echo-ing of the input and I always get "bad file descriptor" errors.
I'd post the file I'm trying to pipe into matchmol.exe, but it's huge (12 Megs).
I'll probably just shunt the results to a file and then open the file. The result file is small enough - I was mostly worried about having to save the 12 Meg file out to a file, run matchmol.exe, and then pull a file back. No biggie. Ralph's code and my finding the CRCRLF gets me uber close to the result.
Thanks for your help!
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.