how to include single quotes from user input in perl
The user is going to enter input string such as Tom's Toy. However the perl script complains saying "unmatched '."
This is my code.
my $commandline="";开发者_如何学Python
while (@ARGV) {
$_ = shift @ARGV;
{$commandline .= $_ . ' ';}
}
print " Running $commandline\n";
system ($commandline);
Now if the user input is Tom's Toy. I just want to print back Tom's Toy. However perl complains "unmatched '.". IF I dont user quote it works fine. (for eg: Tom Toy is good) How do I fix this issue.
Any help is greatly appreciated. Thanks in advance
If you switch things around a little to use the system $cmd, @args
version of the function, no shell will be invoked, so no escaping will be necessary.
my $cmd = shift @ARGV;
my @args = @ARGV;
print " Running $cmd\n";
system $cmd, @args;
I tested with ./test.pl echo Tom\'s Toy
and it gives the expected output:
Running echo
Tom's Toy
system(@ARGV) is probably all you need.
If you give system() a single argument, and if that argument contains any shell metacharacters (including spaces, quotation marks, etc), then the argument will be passed to the shell. jwodder is quite correct: the error message is from the shell, not from Perl.
If you pass system() multiple arguments, it's done without invoking a shell -- which is usually better. The approach you're using takes your program's command-line arguments, joins them together into a single string, then passes that string to the shell, which splits it back into multiple arguments for execution.
On the other hand, sometimes you might want to invoke the shell, for example if you're building up a complex command using pipes, I/O redirection, and so forth, and you don't want to set it all up in Perl. But you have to be careful about metacharacters, as you've seen.
"perldoc -f system" explains this more fully.
If all you want to do is print back the user input, use print
, not system
. system
will try to pass the supplied string to the shell for execution as a command, and it's the shell that's complaining about the unmatched quote.
(Also, instead of manually concatenating @ARGV
, may I direct your attention to the join
function?)
精彩评论