Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I modify a literal regex in Perl 6?

Tags:

raku

Suppose we have a regular inflectional pattern, which cannot be split into segments. E.g. it can be infixation (adding some letters inside the word) or vowel change ('ablaut'). Consider an example from German.

my @words = <Vater Garten Nagel>;
my $search = "/@words.join('|')/".EVAL;

"mein Vater" ~~ $search;                              
say $/;   # 「Vater」

All the three German words form plural by changing their 2nd letter 'a' to 'ä'. So 'Vater' → 'Väter', 'Garten' → 'Gärten', 'Nagel' → 'Nägel'.

Is there a way to modify my $search regex so that it would match the plural forms? Here's what I'm looking for:

my $search_ä = $search.mymethod;
"ihre Väter" ~~ $search_ä;
say $/;  # 「Väter」

Of course, I can modify the @words array and 'precompile' it into a new regex. But it would be better (if possible) to modify the existing regex directly.

like image 914
Eugene Barsky Avatar asked Oct 28 '17 07:10

Eugene Barsky


1 Answers

You can't.

Regexes are code objects in Perl 6. So your question basically reads "Can I modify subroutines or methods after I've written them?". And the answer is the same for traditional code objects and for regexes: no, write them the you want them in the first place.

That said, you don't actually need EVAL for your use case. When you use an array variable inside a regex, it is interpolated as a list of alternative branches, so you could just write:

my @words = <Vater Garten Nagel>; my $search = /@words/;

The regex $search becomes a closure, so if you modify @words, you also change what $search matches.

Another approach to this particular example would be to use the :ignoremark modifier, which makes a also match ä (though also lots of other forms, such as ā or ǎ.)

like image 154
moritz Avatar answered Nov 08 '22 11:11

moritz