在Perl中使用空格执行Windows命令

时间:2018-08-27 09:37:11

标签: windows perl firefox

我的firefox安装在 C:\ Program Files \ Mozilla Firefox 中。

我想尝试阅读 firefox 版本:

open (IN, "\"C:\\Program\ Files\\Mozilla\ Firefox\\firefox.exe\" --version|") or die "Couldn't fork - $!\n";   
my $aarray = (IN); 
print $fh "=========Array Content========> $aarray <====\n";

close(IN);

这很好用。但是,当我将路径或命令放入变量并尝试执行时,它无法显示“无法分叉”

my $ffox = 'C:\Program Files\Mozilla Firefox\firefox.exe';

$ffox =~ s/\\/\\\\/g;  #Replacing single \ with double \\

$ffox =~ s/\ /\\ /g;   # Adding escape character before space 
chop($firefoxVer);  # remove last \n chr.

$ffox =~ s/$/\\\"/g; # With the below two commands, massaging the command to become

$ffox =~ s/^/\\\"/g; # "C:\\Program\ Files\\Mozilla\Firefox\\firefox.exe\"

$firefoxVer = $ffox.' --version|';  # Adding "version|" to the above command  
$firefoxVer =~ s/$/\"/g;     # and make it look like:

$firefoxVer =~ s/^/\"/g;   # "\"C:\\Program\ Files\\Mozilla\\Firefox\\firefox.exe\" --version|"

open (IN, $firefoxVer) or die "Couldn't fork - $!\n"; ==> Fails

1 个答案:

答案 0 :(得分:0)

使用反引号可以直接获得结果,而无需使用open。引用需要保留空格的命令行内容:

use v5.10;
my $version = `"C:\\Program Files\\Mozilla Firefox\\firefox.exe" -version`;
say "version is $version";

如果该目录位于您的路径中,则无需四处寻找

my $firefox = 'C:\\Program Files\\Mozilla Firefox';
$ENV{PATH} .= ";$firefox";
my $version = `firefox -version`;