当字符串中包含双引号时,您需要使用\ 转义它们。
$cmd .= "-U $user_name -P $password -S $host -d master -Q \"BACKUP DATABASE [$database_name] TO DISK = N'$path'\" ";
此外,Perl 允许您使用其他字符作为引号分隔符。 qq 后跟几乎任何字符都与双引号相同。所以你可以这样做来避免使用反斜杠:
$cmd .= qq(-U $user_name -P $password -S $host -d master -Q "BACKUP DATABASE [$database_name] TO DISK = N'$path'" );
$cmd .= qq|-U $user_name -P $password -S $host -d master -Q "BACKUP DATABASE [$database_name] TO DISK = N'$path'" |;
等等……
更新:如何在 Perl 中执行系统命令。有三种基本方式:
system($cmd); #Goes through the shell if shell metacharacters are detected.
system(@command_and_args); #first element is the command, the rest are arguments
system 执行命令并等待它返回。返回值为程序的退出状态。
my @results = `$cmd`; #Always goes through shell.
Backticks 执行命令并返回其输出。仅当您确实需要输出时才应使用它;否则,最好使用system。
exec $cmd;
exec @command_and_args;
exec 与 system 完全相同,只是它永远不会返回。它通过调用另一个程序有效地结束您的程序。
使用最适合您的情况的一种。或者在这种情况下,由于您正在执行 SQL,请考虑使用 DBI 模块。除了几个简单的命令之外,这绝对是一种更好的方法。