Perl6 How to use adverbs as variables?

I am trying to match a string case-sensitive or case-insensitive. Is there a way to make the .match method accept adverbs as variables?

 my $aString = "foo bar baz"; my @anArray = <OO AR AZ>; my $anAdverb = :i; my $firstCheck = ($aString.match(/$anAdverb "@anArray[0]" /)).Bool; 

Using $anAdverb inside a regex does not work. Is there any work?

+5
source share
1 answer

In the context of an expression (i.e., outside of argument lists) :foo creates a Pair object.
This object can then be interpolated as an adverb into the argument list using | :

 my $adverb = :g; say "a 1 b 2".match(/\d/, |$adverb); 

Unfortunately, the .match method .match not support the adverb :i . (Perhaps supervision - perhaps a Rakudo bug report will open.)

I don't think there is a way to interpolate an adverb into a regular expression .

You can save your regular expression as a string and use the <$foo> syntax to evaluate it at run time in one of two different "wrapper" regular expressions (one with :i and one without):

 use MONKEY-SEE-NO-EVAL; my $string = "foo bar baz"; my @array = <OO AR AZ>; my $case-sensitive = True; my $regex = ' "@array[0]" '; say ?$string.match($case-sensitive ?? /:i <$regex>/ !! /<$regex>/); 

However, it is unsafe if any data provided by the user falls into the regular expression.

Of course, if the entire regular expression just matches a literal substring, there is no need for eval, and you can safely interpolate the substring into shell regular expressions as follows:

 my $string = "foo bar baz"; my @array = <OO AR AZ>; my $case-sensitive = True; my $substring = @array[0]; say ?$string.match($case-sensitive ?? /:i $substring/ !! /$substring/); 
+4
source

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


All Articles