我有一个Perl脚本progA.pl
,需要progB.pl
使用该system
命令运行另一个Perl脚本。但是,progB.pl
已被别名化,~/.bashrc
因此我需要确保它~/.bashrc
在加载后运行。我可以通过使用bash
该-lc
选项来实现。
对于这个问题,我考虑了以下版本的内容,以尽可能简化该问题: progB.pl
use feature qw(say);
use strict;
use warnings;
use Data::Dump qw(dd dump);
say "Received \@ARGV: " . dump @ARGV;
这里是progA.pl
:
use feature qw(say);
use strict;
use warnings;
use Data::Dump qw(dd dump);
my $cmd = qq(progB.pl --opt='This option contains '"'"'single'"'"' quotes');
say "cmd = " . dump($cmd);
system( "$cmd" );
say "-----";
system( 'bash -c ' . "$cmd" );
say "-----";
system( 'bash -c ' . "'$cmd'" );
say "-----";
system( "bash -c \"$cmd\"" );
跑步
$ progA.pl
给出输出:
cmd = "progB.pl --opt='This option contains '\"'\"'single'\"'\"' quotes'"
Received @ARGV: "--opt=This option contains 'single' quotes"
-----
Received @ARGV: ()
-----
Received @ARGV: "--opt=This"
-----
Received @ARGV: "--opt=This option contains single quotes"
我们看到,当progB.pl
不使用进行直接运行时,此方法效果很好bash -c
。当我bash -c
用来运行命令时,这三种选择均无法正常工作。
如何progB.pl
使用包含单引号的参数并同时使用using运行bash -c
?
首先应该避免这种疯狂的报价,但是如果您坚持要使用system ARRAY
版本,则应该至少避免一级的报价。
my $cmd = q{progB.pl --opt='This option contains '"'"'single'"'"' quotes'};
system( qw(bash -c), $cmd );
它使它仅是疯狂程度的一种引用。
my $option = q{This option contains 'single' quotes} =~ s/'/'"'"'/gr; # '
my $cmd = qq{progB.pl --opt='$option'};
system( qw(bash -c), $cmd );
在那里你可以做一些简单的帮手
sub sq ($) { "'" . $_[0] =~ s/'/'"'"'/gr . "'" } # "
my $option = q{This option contains 'single' quotes};
my $cmd = qq{progB.pl --opt=@{[sq $option]}};
system( qw(bash -c), $cmd );
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句