Chrys Ugwu Chrys Ugwu - 1 year ago 68
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;

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download