从R - perlQuote/shQuote执行Perl?

mat*_*fee 4 perl r

我正在尝试使用R运行一些Perl system:只需将一个字符串(在R中提供)分配给变量并回显它.(system调用执行/bin/sh)

echo <- function (string) {
    cmd <- paste(shQuote(Sys.which('perl')),
                 '-e',
                 shQuote(sprintf("$str=%s; print $str", shQuote(string))))
    message(cmd)
    system(cmd)
}
# all fine:
# echo('hello world!')
# echo("'")
# echo('"')
# echo('foo\nbar')
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试echo反斜杠(或者实际上任何以反斜杠结尾的字符串),我会收到一个错误:

> echo('\\')
'/usr/bin/perl' -e "\$str='\\'; print \$str"
Can't find string terminator "'" anywhere before EOF at -e line 1.
Run Code Online (Sandbox Code Playgroud)

(注意:前面的反斜杠$很好,因为这可以防止/bin/sh思考$str是一个shell变量).

错误是因为Perl将last \'作为嵌入引号标记解释$str而不是转义反斜杠.事实上,要让perl回应我需要做的反斜杠

> echo('\\\\')
'/usr/bin/perl' -e "\$str='\\\\'; print \$str"
\ # <-- prints this
Run Code Online (Sandbox Code Playgroud)

也就是说,我需要逃避Perl的反斜杠(除了我在R/bash中逃避它们).

如何确保echo用户输入的字符串是打印的字符串?即所需的唯一逃逸级别是在R级别?

即是否存在某种类似的perlQuote功能shQuote?我应该手动转义echo函数中的所有反斜杠吗?我还需要逃脱任何其他角色吗?

ike*_*ami 6

不要生成代码.那很难.相反,将参数作为参数传递:

echo <- function (string) {
    cmd <- paste(shQuote(Sys.which('perl')),
                 '-e', shQuote('my ($str) = @ARGV; print $str;'),
                 shQuote(string))
    message(cmd)
    system(cmd)
}
Run Code Online (Sandbox Code Playgroud)

(您也可以使用环境变量.)

(我之前从未使用过甚至看过R代码,所以请原谅任何语法错误.)