Doing Perl from R - perlQuote / shQuote?

I am trying to run some Perl from R using system : simply assigning the string (provided in R) to a variable and repeating it. (a system call is made in /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') 

However, if I try to echo backslash (or even any line ending with a backslash), I get an error message:

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

(Note: the backslash in front of $ fine, as it protects /bin/sh from thinking $str is a shell variable).

The error is that Perl interprets the last \' as an inline quote mark inside $str , and not an escape backslash. In fact, to get perl for the backslash echo, I need to do

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

That is, I need to avoid the backslash for Perl (in addition to the fact that I avoid them in R / bash).

How can I ensure in echo that the line the user enters is the line that is being printed? that is, the only shielding level that is needed is at level R?

i.e. is there any perlQuote function similar to shQuote ? Should I just avoid all the backslashes in my echo function? Are there any other characters that I need to avoid?

+4
source share
2 answers

Do not generate code. It's hard. Instead, pass the argument as an argument:

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

(You can also use the environment variable.)

(I had never used or even seen R code before, so I apologize for any syntax errors.)

+6
source

The following seems to work. In Perl, I use q// instead of quotation marks to avoid problems with shell quotation marks.

 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("\\\\") 
+3
source

Source: https://habr.com/ru/post/1481592/


All Articles