In the code below, the Regex $r
clearly "knows" that it contains the text bar
– that's how it is able to match against the Str bar
. But .gist
and .raku
report that $r
contains the variable $foo
without saying what value $foo
contains. Is there any way to get $r
to tell me its computed value?
sub f {
my $foo = 'bar';
g(rx/$foo/);
}
sub g($r) {
say $r.gist;
say 'bar' ~~ rx/$r/;
}
f # OUTPUT: rx/$foo/
# 「bar」
(I know that I can access the same information by manually parsing $r
, finding all variables, and then walking &g
's callframe
s to find the values of the variables. But that seems like a fairly brittle hack to get at info that the Regex clearly already knows, at least on some level.)
Can I introspect a Regex's interpolated value?
No, because it hasn't been interpolated, just like in a closure { say $a }
we'd not consider $a
as being interpolated either, but rather say that it is closed over. A variable in a regex compiles into a lookup of that variable, the lookup being made each time the regex is evaluated. This can be confirmed by changing the value of the variable between evaluations of the regex:
my $var = "foo";
my $rx = rx/$var/;
say "foobar" ~~ $rx; # 「foo」
$var = "bar";
say "foobar" ~~ $rx; # 「bar」
The larger principle at work here is that in Raku, regexes are not strings that are handled by some regex implementation in the standard library, but instead parts of the compiled program, and subject to the same closure semantics as any other block or thunk.
That they gist
to their source is mostly there for pragmatic reasons (better diagnostic output in the Test
module was probably the driving force), however it is done precisely by the source code string being attached to the Regex
object at compile time. By runtime, it's all bytecode, and the source string you see isn't involved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With