Chrys Ugwu Chrys Ugwu - 1 month ago 8
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
<code/>$1</code>
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;

Answer

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.

#!/usr/bin/perl
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";
$re->($string);

print $string;

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

Hope this is helpful.

Comments