Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I introspect a Regex's interpolated value?

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 callframes 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.)

like image 256
codesections Avatar asked Apr 20 '21 13:04

codesections


1 Answers

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.

like image 91
Jonathan Worthington Avatar answered Sep 27 '22 18:09

Jonathan Worthington