Reputation: 39158
sub make-regex {
my $what's-in-the-box = rand > .5 ?? 'x' !! 'y';
/$what's-in-the-box/
}
my $lol-who-knows = make-regex;
$lol-who-knows.gist.say;
How do you see the innards of the regex (i.e. x
or y
)? Forcing a match is not a solution.
Upvotes: 7
Views: 170
Reputation: 32404
How do you see the innards of the regex (i.e.
x
ory
)?
You:
Statically compile the regex. Doing so will involve use of a raku compiler, i.e. Rakudo.
Dynamically evaluate the regex so that the $what's-in-the-box
variable in your regex gets interpolated and turns into x
or y
. Doing so will involve running the regex as code. That in turn means both using Rakudo and running the regex with a Match
object invocant (or sub-class instance or, conceivably, a mock object equivalent).
View the resulting regex. Doing so will involve using compiler (Rakudo) toolchain specific introspection or debug functionality.
Forcing a match is not a solution.
You can run a regex with no input if your concern is just to avoid the need for a successful match:
say Match.new.&$lol-who-knows; # #<failed match>
But it must be run, otherwise the $what's-in-the-box
variable won't turn into an x
or y
. You might think you could cheat on this by writing something that mimics this part of raku regex construction/use but there's good reason to think that's not going to work out[1].
And then you must view its innards, using Rakudo toolchain features, after you've started running it and before it finishes running.
In raku, a Regex
is code, a sub-class of Method
.
Until you run it, by using it in a match, that code is just /$what's-in-the-box/
(aka regex { $what's-in-the-box }
). It's the equivalent of something like:
method {
...self should be a Match or a sub-class of it
...if self is not an instance, create a new one
...do matching -- compiler evaluates $what's-in-the-box during this
...return updated self / new instance
}
(To see a bit more detail, see Moritz's answer to the SO Can I change the slang inside a method?.)
You create your regex inside the closure named make-regex
. The compiler spots that you've used $what's-in-the-box
and therefore hangs on to the variable even after the make-regex
closure returns. Later on, if/when your regex is run, the $what's-in-the-box
variable will be replaced by its value at the moment the regex is run.
[1] There are plenty of huge complications you'll encounter if you try to do an end-run around using the compiler. Even something simple like interpolation is non-trivial. To quote Jonathan Worthington, in 2020:
I thought oh I'm only building [a tool that's] not the real compiler. I can ... have a simpler model of the symbol resolution. In the end it turned out that no I couldn't really. That started to create us some problems. When we aligned the way that we resolved symbols with the same algorithms and lookup structures that was being used in the compiler then suddenly it all became a lot simpler.
Upvotes: 6