in reply to CGI Script Calling Grep

I am not sure of exactly what you are trying to do with your code, but it seems to me it should be much easier:
my @grep_result = `grep -r $string .`; foreach my $result (@grep_result) { print; }
HTH
Scott

update: Ack! yes of course; I don't write CGIs much, but I should still know better. Use -T and untaint $string, by all means.

Replies are listed 'Best First'.
Re: Re: CGI Script Calling Grep
by muleherd (Initiate) on Sep 26, 2001 at 00:12 UTC
(arturo) Re: CGI Script Calling Grep
by arturo (Vicar) on Sep 26, 2001 at 00:12 UTC

    Well, yes, in one way (this should solve the technical problem), and in another, emphatic no. Never pass user input directly to a subshell -- all sorts of nasties could result. Suppose $string is "foo *; cat /etc/passwd; rm -rf " for example. DoS, cracker info, and evil file removal (potential) all in one go.

    So you could use this sort of thing, but *not* without taint checking, and, if you're going to untaint, be sure you know what you're doing. For more, see perldoc perlsec on your system, or perlsec hereabouts.

    perl -e 'print "How sweet does a rose smell? "; chomp ($n = <STDIN>); +$rose = "smells sweet to degree $n"; *other_name = *rose; print "$oth +er_name\n"'
Re: Re: CGI Script Calling Grep
by perrin (Chancellor) on Sep 26, 2001 at 00:15 UTC
    Not recommended for certain values of $string... (scain probably knew that, but some people might not.)

    Your exec didn't do what you want because... well, that's not what exec does. It doesn't capture output. Read the docs on exec, system, and backticks (``) for a better understanding. It would be safer and faster to do this using File::Find and Perl's built-in pattern matching.

      Your exec didn't do what you want because... well, that's not what exec does. It doesn't capture output. Read the docs on exec, system, and backticks (``) for a better understanding.

      Actually, he's running grep in a reasonable way. The open() call sets up a pipe, forks, and hooks the pipe to the child process's stdout; he then execs grep in the subshell. The way he's exec'ing grep, he also avoids the question of shell metacharacters in the $string variable.

      Scain: The problem may be the script's current directory. The script is running grep (recursively) on ".". When you run the script by hand you could be starting it in the directory you want grep to search. The web server probably starts the script with a different directory as its current directory, so your script would have to chdir() to the right spot, or else give the full /path/to/the/directory instead of using ".".

        Oh, good point. I assumed he wanted to format the output as HTML.