I've been playing in Perl 6 (after several years of absence).  I
am very impressed.

I'm porting my recent Date::Reformat into Perl 6, for fun,
to get me back into the Perl 6 headspace, and possibly to help
others, either with something useful, or something they can look
to for examples.

I've run into a snag, in that my strptime processing in Perl 5
relies on building a string that looks like a regex with named
captures, and then interpolating that into a real regex.

In Perl 6, while I am able to interpolate, and match, capturing
does not appear to be allowed/implemented via interpolation (and
there is no quotemeta).

    my $pattern = Q/$<greeting>=[hello]/;
    my $string = Q/hello/;

    # Interpolated regex matches, but does not capture.
    my $regex = rx/<{$pattern}>/;

    # EVALed regex matches and captures.
    my $regex_eval = EVAL "rx/" ~ $pattern ~ "/";

Of course, there may be a better way, since regex interpolation
seems frowned upon in Perl 6.

One idea I have is to generate a grammar, but the only way I've
been able to get that to work is to create a string that looks
like a grammar, and EVAL it.  Is that a Perl 6 best-practice, or
is there a better way?

    my $generated_grammar = generate_grammar(
        top   => Q/<year> '-' <month> '-' <day>/,
        year  => Q/\d**4/,
        month => Q/\d\d?/,
        day   => Q/\d\d?/,
    );
    my $match = $generated_grammar.parse($date_string);
    say $match.perl;

    sub generate_grammar (*%tokens) {
        my $grammar_string = 'my grammar { rule TOP { ';

        # Populate TOP.
        $grammar_string ~= %tokens<top>;
        $grammar_string ~= ' };';

        # Define regexes.
        for %tokens.kv -> $name, $regex {
            next if $name eq 'top';
            $grammar_string ~= " regex $name \{ $regex \};";
        }

        $grammar_string ~= ' }';

        # EVAL into a useable grammar.
        say "EVALing grammar into existence: $grammar_string";
        my $grammar = EVAL $grammar_string;
        return $grammar;
    }

It seems like it might be cool to create an action class that
will build a grammar to parse a date in a given format, as an
strptime format string is being parsed.  I'm not quite sure yet
what that looks like.

-kolibrie

Attachment: signature.asc
Description: Digital signature

Reply via email to