Executing Perl 6 code in Rmarkdown

后端 未结 3 1848
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-19 22:33

I want to write some tutorials on Perl 6. For this I believe Rmarkdown would be of great help.

So I am trying to execute Perl 6 code within Rmarkdown docum

3条回答
  •  名媛妹妹
    2021-02-19 23:08

    Not my area of expertise, but with a help of a blog I managed to get it to produce output.

    First, look in RStudio's R Markdown tab. It shows you a warning that explains why your version isn't rendering anything:

    Warning message:
    In get_engine(options$engine) :
      Unknown language engine 'perl6' (must be registered via knit_engines$set()).
    

    So with that in mind, we can look up how to register an engine and do so:

    ```{r setup, echo=FALSE}
    library(knitr)
    eng_perl6 <- function(options) {
      # create a temporary file
      f <- basename(tempfile("perl6", '.', paste('.', "perl6", sep = '')))
      on.exit(unlink(f)) # cleanup temp file on function exit
      writeLines(options$code, f)
      out <- ''
    
      # if eval != FALSE compile/run the code, preserving output
      if (options$eval) {
        out <- system(sprintf('perl6 %s', paste(f, options$engine.opts)), intern=TRUE)
      }
    
      # spit back stuff to the user
      engine_output(options, options$code, out)
    }
    
    knitr::knit_engines$set(perl6=eng_perl6)
    ```
    
    ```{r, engine='perl6'}
    my $s= "knitr is really good";
    say $s;
    ```
    

    The engine is registered with a function that first saves the code to run to a temporary file and then executes the Rakudo compiler, asking it to compile that file.

    After collecting the needed output, the function deletes the temporary file and gives us the output for rendering.

提交回复
热议问题