sid_com
sid_com

Reputation: 25117

How to interpolate a variable into a regex-pattern in the regex part of a substitution?

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]";

Upvotes: 9

Views: 274

Answers (1)

timotimo
timotimo

Reputation: 4329

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.

Upvotes: 10

Related Questions