Can I change literal regex in Perl 6?

Suppose we have a regular inflectional pattern that cannot be segmented. For instance. it can be an infix (adding some letters inside a word) or a change in vowels ('ablaut'). Consider an example from the German language.

my @words = <Vater Garten Nagel>; my $search = "/@words.join('|')/".EVAL; "mein Vater" ~~ $search; say $/; # 「Vater」 

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

Is there a way to modify my $search regex to match multiple forms? Here is what I am looking for:

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

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

+5
source share
1 answer

You can not.

Regexes are code objects in Perl 6. So your question basically reads: "Can I change routines or methods after I write them?". And the answer is the same for traditional code objects and for regular expressions: no, write to them that you want them first.

However, you really don't need EVAL for your use case. When you use an array variable inside a regular expression, it is interpolated as a list of alternative branches, so you can simply write:

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

The $search regular expression becomes a closure, so if you change @words you will also change the match of $search .

Another approach to this particular example would be to use a modifier :ignoremark , which makes a also match ä (although there are also many other forms, such as ā or ǎ .)

+7
source

Source: https://habr.com/ru/post/1272957/


All Articles