Can I change the Perl 6 slang inside a method?

前端 未结 1 1748
忘了有多久
忘了有多久 2020-12-19 21:01

A Perl 6 Regex is a more specific type of Method, so I had the idea that maybe I could do something black-magicky in a regular method that produces the same thing. I particu

相关标签:
1条回答
  • 2020-12-19 21:44

    First of all, the Perl 6 design documents mandate an API where regexes return a lazy list of possible matches. If Rakudo adhered to that API, you could easily write a method that acted as a regex, but parsing would be very slow (because lazy lists tend to perform much worse than a compact list of string positions (integers) that act as a backtracking stack).

    Instead, Perl 6 regexes return matches. And you can do the same. Here is an example of a method that is called like a regex inside of a grammar:

    grammar Foo {
        token TOP { a <rest> }
    
        method rest() {
            if self.target.substr(self.pos, 1) eq 'b' {
                return Match.new(
                    orig   => self.orig,
                    target => self.target,
                    from => self.pos,
                    to   => self.target.chars,
                );
            }
            else {
                return Match.new();
            }
        }
    }
    
    say Foo.parse('abc');
    say Foo.parse('axc');
    

    Method rest implements the equivalent of the regex b.*. I hope this answers your question.

    Update: I might have misunderstood the question. If the question is "How can I create a regex object" (and not "how can I write code that acts like a regex", as I understood it), the answer is that you have to go through the rx// quoting construct:

    my $str = 'ab.*';
    my $re = rx/ <$str> /;
    
    say 'fooabc' ~~ $re;       # Output: 「abc」
    
    0 讨论(0)
提交回复
热议问题