@@ -826,21 +826,30 @@ of type L<Cool> are coerced to C<Str> for literal matching.
826
826
my $another-string = $some-string.subst(/foo/, "string"); # gives 'Some string'
827
827
$some-string.=subst(/foo/, "string"); # in-place substitution. $some-string is now 'Some string'
828
828
829
- = head3 Closures
829
+ = head3 Callable
830
830
831
- The replacement can be a closure:
831
+ The replacement can be a L < Callable > in which the current L < Match > object will be
832
+ placed in the C < $/ > variable, as well as the C < $_ > topic variable.
833
+ No thunking of arguments is done, so you need to use a L < Callable > replacement, to
834
+ refer to any of the captures made in the regex:
832
835
836
+ # Using capture from $/ variable (the $0 is the first positional capture)
837
+ say 'abc123defg'.subst(/(\d+)/, { " before $0 after " });
838
+ # OUTPUT: «abc before 123 after defg»
839
+
840
+ # Using capture from $/ variable (the $<foo> is a named capture)
841
+ say 'abc123defg'.subst(/$<foo=\d+/, { " before $<foo> after " });
842
+ # OUTPUT: «abc before 123 after defg»
843
+
844
+ # Using WhateverCode to operate on the Match given in $_:
845
+ say "abc123defg".subst(/(\d+)/, *.flip);
846
+ # OUTPUT: «abc321defg»
847
+
848
+ # Using a Callable to generate substitution without involving current Match:
833
849
my $i = 41;
834
850
my $str = "The answer is secret.";
835
851
my $real-answer = $str.subst(/secret/, {++$i}); # The answer to everything
836
852
837
- = head3 Captures
838
-
839
- If you are going to use captures, you have to use a closure like so:
840
-
841
- say 'abc123defg'.subst(/(\d+)/, { " before $0 after " })
842
- # OUTPUT: «abc before 123 after defg»
843
-
844
853
= head3 More Examples
845
854
846
855
Here are other examples of usage:
0 commit comments