How to pass a regex as an argument to a routine in Perl 6

Maybe I'm doing something completely wrong, but is there a way to change and combine regexesusing subroutines? The program below will not compile.

sub a(Regex $r1) {
  return rx/ <$r1> a /
}

my regex letter_b { b };

my $new = a(letter_b);
say $new;
+4
source share
2 answers

Looking at the documentation for Regex, he says:

A named Regexcan be defined using a regex declaration, and then defined in curly braces. As any regexp does Callable, introspection requires reference via &-sigil.

my regex R { \N };
say &R.^name; # OUTPUT: «Regex␤»

Besides the Grammardocumentation (for the concept, not the type), it explains more about this:

. Perl 6 Regexes , , :

my regex number { \d+ [ \. \d+ ]? }

, my, .

, :

say so "32.51" ~~ &number;                                    # OUTPUT: «True␤»
say so "15 + 4.5" ~~ / <number> \s* '+' \s* <number> /        # OUTPUT: «True␤»

, regex a, , , :

my $new = a(&letter_b);
#           ^
#  This is what you need!

say $new;
say so "ba" ~~ $new;         # OUTPUT: «True␤»
say so "ca" ~~ $new;         # OUTPUT: «False␤»
+8

, &.

, <$r1>, , P6 $r1 - Regex. :

sub a(Regex $r1) {
  return rx/ $r1 a /
}

my regex letter_b { b };

my $new = a(&letter_b);
say $new;                # rx/ $r1 a /
say 'ba' ~~ $new;        # 「ba」

, ...

a(letter_b) letter_b, . ( a, , letter_b, a.)

letter_b ,

say Regex ~~ Method; # True

invocant arg:

say &letter_b.signature; # (Mu $: *%_)

. :

Too few positionals passed; expected 1 argument but got 0

, .

+3

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


All Articles