9

What do I have to change here to make it work?

my $str = "start middle end";
my $regex = / start ( .+ ) end /;
$str.=subst( / <$regex> /, { $0 } ); # dies: Use of Nil in string context
say "[$str]";
Toto
  • 89,455
  • 62
  • 89
  • 125
sid_com
  • 24,137
  • 26
  • 96
  • 187

1 Answers1

10

The problem is that interpolating a regex into another regex via the <$regex> syntax will not install a result in the match variable. There's two ways to get around this:

  • The easiest way is to just use the regex directly in subst, i.e. $str .= subst($regex, { $0 });
  • Give the interpolated regex an explicit name and access the result via that, i.e. $str .= subst( / <foo=$regex> /, { $<foo>[0] });

Both of these should work fine.

timotimo
  • 4,299
  • 19
  • 23
  • +1 I feel like I should have known it already but I didn't: you can just drop a regex var into `< ... >` and have it function as an inserted regex. And to think I've been generating complex escaped strings to dump in with `<{ ... }>`. D'oh. – user0721090601 Apr 19 '19 at 19:05
  • From the "traps to avoid" [documentation](https://docs.perl6.org/language/traps#%3C%7B%24x%7D%3E_vs_%24%28%24x%29%3A_Implicit_EVAL): Internally <{…}> EVAL-s the given string inside an anonymous regex, while $(…) lexically interpolates the given string. So <{…}> immediately breaks with more complicated inputs. and later > Therefore, try not to use <{}> unless you really need EVAL. – LuVa Apr 19 '19 at 20:02
  • See related: https://stackoverflow.com/q/71057626/7270649 – jubilatious1 Mar 29 '22 at 23:39