Skip to content

Commit f99445f

Browse files
committed
Revert "Revert "Restructure .subst with Callables section""
This reverts commit 8ef3c50.
1 parent 8ef3c50 commit f99445f

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

doc/Type/Str.pod6

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -826,21 +826,30 @@ of type L<Cool> are coerced to C<Str> for literal matching.
826826
my $another-string = $some-string.subst(/foo/, "string"); # gives 'Some string'
827827
$some-string.=subst(/foo/, "string"); # in-place substitution. $some-string is now 'Some string'
828828
829-
=head3 Closures
829+
=head3 Callable
830830
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:
832835
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:
833849
my $i = 41;
834850
my $str = "The answer is secret.";
835851
my $real-answer = $str.subst(/secret/, {++$i}); # The answer to everything
836852
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-
844853
=head3 More Examples
845854
846855
Here are other examples of usage:

0 commit comments

Comments
 (0)