调用系统命令时如何处理 Perl 中的引号?

How to handle quotes in Perl when calling system commands?

我正在尝试制作一个非常简单的脚本来从 .desktop 文件调用 PDFXchange 查看器。但我无法做到这一点,因为 bash 看到了我不知道的东西:

#!/usr/bin/perl

use strict;
use warnings;

my $winepath = `winepath -w -0 "$ARGV[0]"`;

my $cmd=join ' ',
    'wine',
    '\'C:\Program Files\Tracker Software\PDF Viewer\PDFXCview.exe\'',
    "\'$winepath\'";

print $cmd . "\n";

exec $cmd;

输出

$ exec_pdfxcv 'pdf with spaces.pdf' 
wine 'C:\Program Files\Tracker Software\PDF Viewer\PDFXCview.exe' 'Z:\media\FILES\pdf with spaces.pdf'\nsh: 1: Syntax error: Unterminated quoted string

我是 Perl 的初学者,所以在尝试了几次不同的引号配置后,我 运行 很快就摆脱了想法。

有什么想法吗?

看来你在这里躲过了(常见的难以理解的引号和转义符),因为你不需要 shell 来完成完成的事情,其余的也不需要太多.

然后也使用 exec, which bypasses the shell altogether. This can be done with system 的列表形式,但是,唉,不要使用反引号。

my $winepath = `winepath -w -0 "$ARGV[0]"`;
chomp $winepath;

my @cmd = (
    'wine', 
    q('C:\Program Files\Tracker Software\PDF Viewer\PDFXCview.exe'),
    "'$winepath'"
); 
exec @cmd;

注意使用 q (perlop) 作为单引号,释放符号 ' 在里面使用。

我们应该从 $winepath 中删除换行符(由 qx 返回)并且需要通过在其周围添加 ' 来保护其中的空格。

经历 shell 只会让事情变得更难;仅当您 特别 需要 shell.

时才这样做

一旦您确实需要shell,但是,请注意ShellQuote and Win32::ShellQuote

我试了一百次终于成功了。

#!/usr/bin/perl

use strict;
use warnings;

my $winepath = `winepath -w -0 "$ARGV[0]"`;

exec 'wine', q(C:\Program Files\Tracker Software\PDF Viewer\PDFXCview.exe), "".$winepath."";

希望对大家有所帮助!

如果有人对 .desktop 文件感兴趣:

[Desktop Entry]
Name=PDF XChange Viwer
Comment=View multi-page documents
Exec=exec_pdfxcv %U
StartupNotify=true
Terminal=false
Type=Application
StartupWMClass=PDFXCview.exe
Icon=evince
Categories=GNOME;GTK;Office;Viewer;
MimeType=application/pdf;application/x-bzpdf;application/x-gzpdf;application/x-xzpdf;application/x-ext-pdf;application/postscript;application/x-bzpostscript;application/x-gzpostscript;image/x-eps;image/x-bzeps;image/x-gzeps;application/x-ext-ps;application/x-ext-eps;application/x-dvi;application/x-bzdvi;application/x-gzdvi;application/x-ext-dvi;image/vnd.djvu;image/vnd.djvu+multipage;application/x-ext-djv;application/x-ext-djvu;image/tiff;application/x-cbr;application/x-cbz;application/x-cb7;application/x-cbt;application/x-ext-cbr;application/x-ext-cbz;application/vnd.comicbook+zip;application/x-ext-cb7;application/x-ext-cbt;application/oxps;application/vnd.ms-xpsdocument;