Quick actions

cmd+k|ctrl+k

Navigation

Languages

StackOverflow: Capture and execute multiline code and incorporate result in Perl 6

Snippet info

Language

Raku

Visibility

public

Author

raiph

Created

2019-07-28T12:15:01Z

Updated

2019-07-28T17:13:05Z

# See https://stackoverflow.com/questions/57127263/capture-and-execute-multiline-code-and-incorporate-result-in-perl-6

use v6;

constant $ticks = '```';

my regex Search {
  $ticks '{perl6 evaluate=' $<evaluate>=(TRUE|FALSE) '}'
  $<code>=[<!before $ticks> .]*
  $ticks
}

sub Replace ($/) {
  "Code:\n" ~ $ticks ~ $<code> ~ $ticks ~
    ($<evaluate> eq 'TRUE'
      ?? "\n\n" ~ 'Output:' ~ "\n" ~ $ticks ~ "\n" ~ Evaluate($<code>) ~ $ticks
      !! '');
}

sub Evaluate ($code) {
  my $out; my $*OUT = $*OUT but role { method print (*@args) { $out ~= @args } }
  use MONKEY; my $eval-result = EVAL $code;
  $out // $eval-result ~ "\n"
}

spurt
  'example_new.md',
  slurp('example.md')
    .subst: &Search, &Replace, :g;

say slurp 'example_new.md';
INFO