【问题标题】:Execute Windows command with spaces in Perl在 Perl 中执行带空格的 Windows 命令
【发布时间】:2019-02-01 19:46:19
【问题描述】:

我的 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

【问题讨论】:

  • chomp 没有帮助。它没有执行命令并读取命令的输出流。
  • 是试图只获取版本,还是试图创建一个以版本为文件名的文件句柄?

标签: windows perl firefox


【解决方案1】:

使用反引号,您可以直接获得结果,而无需 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`;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多