从R-perlQuote/shQuote执行Perl?

从R-perlQuote/shQuote执行Perl?,r,perl,R,Perl,我试图使用系统从R运行一些Perl:只需将一个字符串(在R中提供)分配给一个变量并进行回显。(系统调用在/bin/sh中执行) (注意:$前面的反斜杠很好,因为这样可以防止/bin/sh认为$str是一个shell变量) 错误是因为Perl将最后一个\'解释为$str中的嵌入引号,而不是转义的反斜杠。事实上,要让perl回显反斜杠,我需要执行以下操作 > echo('\\\\') '/usr/bin/perl' -e "\$str='\\\\'; print \$str" \ # <

我试图使用
系统
从R运行一些Perl:只需将一个字符串(在R中提供)分配给一个变量并进行回显。(系统调用在
/bin/sh
中执行)

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

错误是因为Perl将最后一个
\'
解释为
$str
中的嵌入引号,而不是转义的反斜杠。事实上,要让perl回显反斜杠,我需要执行以下操作

> echo('\\\\')
'/usr/bin/perl' -e "\$str='\\\\'; print \$str"
\ # <-- prints this
回声(“\\\”) “/usr/bin/perl'-e”\$str='\\\\\';print\$str”
\#以下方法似乎有效。 在Perl中,我使用
q/
而不是引号来避免shell引号的问题

perlQuote <- function(string) {
  escaped_string <- gsub("\\\\", "\\\\\\\\", string)
  escaped_string <- gsub("/", "\\/", escaped_string)
  paste("q/", escaped_string, "/", sep="")
}
echo <- function (string) {
    cmd <- paste(shQuote(Sys.which('perl')),
                 '-le',
                 shQuote(sprintf("$str=%s; print $str", perlQuote(string))))
    message(cmd)
    system(cmd)
}
echo(1)
echo("'"); echo("''"); echo("'\""); echo("'\"'")
echo('"'); echo('""'); echo('"\''); echo('"\'"'); 
echo("\\"); echo("\\\\")

perlQuote不生成代码。那很难。而是将参数作为参数传递:

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

echo(我正在尝试为R制作一个
cowsay
包,以便与
fortunes
包结合,所以这个问题是为了一个好的理由!)
perlQuote <- function(string) {
  escaped_string <- gsub("\\\\", "\\\\\\\\", string)
  escaped_string <- gsub("/", "\\/", escaped_string)
  paste("q/", escaped_string, "/", sep="")
}
echo <- function (string) {
    cmd <- paste(shQuote(Sys.which('perl')),
                 '-le',
                 shQuote(sprintf("$str=%s; print $str", perlQuote(string))))
    message(cmd)
    system(cmd)
}
echo(1)
echo("'"); echo("''"); echo("'\""); echo("'\"'")
echo('"'); echo('""'); echo('"\''); echo('"\'"'); 
echo("\\"); echo("\\\\")
echo <- function (string) {
    cmd <- paste(shQuote(Sys.which('perl')),
                 '-e', shQuote('my ($str) = @ARGV; print $str;'),
                 shQuote(string))
    message(cmd)
    system(cmd)
}