简体   繁体   English

Perl中的单引号和双引号

[英]Single quotes and double quotes in perl

I'm a newbie in perl and I'm trying to execute an operating system command from a Perl script. 我是Perl的新手,并且正在尝试从Perl脚本执行操作系统命令。

The operating system command is executed with IPC::Open3 , and the command is like 操作系统命令是使用IPC::Open3执行的,该命令类似于

$cmd = "mycommand --add \"condition LIKE '%TEXT%' \"";

This command is supposed to insert the string contained after the "add" into a database. 该命令应该将包含在“添加”之后的字符串插入数据库。

The problem is that it inserts the record in the database without the single quotes around %TEXT% , like this: 问题是它将记录插入数据库中,而在%TEXT%周围没有单引号,如下所示:

condition LIKE %TEXT%

If I execute the command at a command prompt it inserts the string correctly. 如果我在命令提示符处执行命令,它将正确插入字符串。

How should I format the double and single quotes so that it is inserted in the database correctly? 我应该如何格式化双引号和单引号,以便正确地将其插入数据库中?

Thanks for the help 谢谢您的帮助

By putting the command in a single string, you are inflicting upon it a pass through your system's shell. 通过将命令放在单个字符串中,就使该命令穿过系统的外壳。 (You don't mention if it's cmd.exe or bash or other fun stuff.) (您不会提及它是cmd.exe还是bash或其他有趣的东西。)

Suggestions: 建议:

  1. Creating your system command as an array of strings will avoid the shell re-interpolating your command line. 将系统命令创建为字符串数组将避免外壳程序重新插入命令行。 @cmd = ('mycommand', '--add', q(condition LIKE '%TEXT%'));

  2. Throw in extra backslashes to protect the single quotes from your shell. 加上额外的反斜杠以保护shell中的单引号。 Prepending echo to your command could help with the debugging.... 在命令前添加echo可能有助于调试。

  3. (my personal favorite) Don't shell out for your Database access. (我个人最喜欢的)不要为您的数据库访问而掏腰包。 use DBI . use DBI

$cmd = q{mycommand --add "condition LIKE '%TEXT%'"};

qq is for double-quoting , q is for single quoting. qq用于双引号, q用于单引号。

This way it takes whole command as it is. 这样,它可以照原样接收整个命令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM