Oops, forgot to hit "reply-all" this morning... similar answer to
Laurent's with slightly different implementation.

-y


---------- Forwarded message ---------
From: yary <not....@gmail.com>
Date: Tue, Aug 28, 2018 at 8:43 AM
Subject: Re: A grammar to provide substitution

this is simple enough to not require a grammar, a regular expression
substitution will do. Let's say that any unknown variables should be
marked...


#!/usr/bin/env perl6

my Str $source = '$(greeting), $(name). What do you think about $(any-topic)?';

my Str $output = format-string(
        $source,
        name => "Earthling",
        any-topic => "life on other planets",
    );

say $output;  # $(I do not know your greeting), Earthling. What do you
think about life on other planets?

sub format-string(Str:D $source, *%vars  --> Str:D) {
    return $source.subst(
             / '$('         # Start looking for a named var
               (            # Capture it in $0
                 <[\w -]>+  # name is any mix of "word" chars and dash
               )            # end capture
               ')'          # Stop looking for the var
             /,
             {
               %vars{$0} // '$(I do not know your ' ~ $0 ~ ')'
             },
             :g
           );
}

Reply via email to