views:

50

answers:

2

I find myself needing to use Perl more and more since PHP's regular expressions leave me wondering what is going on half the time as they simply don't respond as they should (as they do when I use Perl, for example)... i had been using this method to call perl (before i started trying to do this with regular expressions).. passing in a regex string as a variable causes all sorts of problems, such as using " ( )" anywhere makes it not work, among other things.. I am wondering if there is a better way to do this, than the string of variables after the perl filename method as it seems to have some glaring limiations.. thanks for any info.

the way I do it currently:

$file = "/pathtomy/perlscript.pl $var1 $var2 $var3" ;
    ob_start();
passthru($file);
$perlreturn = ob_get_contents();
ob_end_clean();
return $perlreturn;
A: 

Try to use quotation marks:

$file = "/pathtomy/perlscript.pl '$var1' '$var2' '$var3'" ;
polemon
sounds simple enough.. I guess I didn't think of it that way as I that makes sense now that I think about it as perl wouldn't see it with the quotations the way I was doing it since the entire filestring is enclosed in quotations
Rick
solved it.. thanks
Rick
@Rick it's not perl, it's the shell that's getting in between when you use `passthru`.
hobbs
This code can create serious problems with strings that contain single quotes. Please use gbacon's answer instead.
janmoesen
+2  A: 

For the general case, you'll want to use escapeshellarg. Blindly wrapping everything in single quotes works most of the time but will fail when one of your arguments contains a single quote!

string escapeshellarg  ( string $arg )

escapeshellarg() adds single quotes around a string and quotes/escapes any existing single quotes allowing you to pass a string directly to a shell function and having it be treated as a single safe argument. This function should be used to escape individual arguments to shell functions coming from user input. The shell functions include exec(), system() and the backtick operator.

Using a simple Perl program that prints its command-line arguments

#! /usr/bin/perl

$" = "][";  # " fix StackOverflow highlighting
print "[@ARGV]\n";

and then a modified version of the PHP program from your question

<?php

$var1 = "I'm a";
$var2 = "good boy,";
$var3 = "I am.";

$file = "./prog.pl " . implode(" ",
                         array_map("escapeshellarg",
                           array($var1,$var2,$var3)));
echo "command=", $file, "\n";

ob_start();
passthru($file);
$perlreturn = ob_get_contents();
ob_end_clean();
echo "return=", $perlreturn;

?>

we see the following output:

$ php prog.php 
command=./prog.pl 'I'\''m a' 'good boy,' 'I am.'
return=[I'm a][good boy,][I am.]
Greg Bacon