Chrys Ugwu Chrys Ugwu - 8 days ago 4x
Perl Question

perl regex dynamic capturing

Is there a way to set a dynamic capture unit

my $pattern = '`(.*?)`';
$string =~ s{$pattern}{<code/>$1</code>}im;

But instead of passing
directly to replace, i want to store it as a variable (which may defer depending on the type of data i want to capture)

my $pattern = '`(.*?)`';
my $replace = '<code/>$1</code>'; #or my $replace = '<code/>$2</code>'
$string =~ s{$pattern}{$replace}im;


In this post, Jenda offers a solution that may be applicable to your case. It involves creating a sub and then evaluating the sub to a regex.

use strict;
use warnings;

my $pattern = '`(.*?)`';
my $replace = '<code/>$1</code>';
my $code = 'sub {$_[0] =~ s{$pattern}{'. $replace . '}ig}';
my $re = eval $code;

my $string = "Here `is` a string";

print $string;

This prints Here <code/>is</code> a string

Hope this is helpful.