Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks! My script does stuff like this:
$x = `foo \"$filename\" | bar | baz`;
so the shell gets invoked. I'm worried about the case where the filename contains characters " \ $ and so forth. (i.e., ones that have special meaning for the shell even when in double-quotes) - how do I protect from that? Would
$filename =~ s/(["\\\$])/\\$1/g
be foolproof? Is there a better alternative to using backticks in this situation?

Replies are listed 'Best First'.
Re: quoting for backticks
by Jaap (Curate) on Nov 01, 2002 at 10:36 UTC
    if ($filename =~ m/^([a-zA-Z0-9\.\_\-\/\\]+)$/) { $filename = $1 $x = `foo \"$filename\" | bar | baz`; } else { print "The filename you entered contains illegal characters."; }
    This is now untainted too, if you know something about tainting.
Re: quoting for backticks
by Anonymous Monk on Nov 01, 2002 at 06:06 UTC
    $x = `foo "\Q$filename\E" | bar | baz`;
      that should be
      $x = `foo \Q$filename\E | bar | baz`
      (??)