2

I am using eval to handle a dynamic replacement regular expression.

The value capture on the left side ($1) is not being used on the right side of the regexp.

#!/usr/bin/perl
use strict;

my $string = "test-txt";

# Attempt 1
my $regexp_m = '-(\S+)$';
my $regexp_r = '.$1';
my $string2 = eval{ $string =~ s/$regexp_m/$regexp_r/; return $string; };

# Attempt 2
my $regexp = 's/(\S+)$/.$1/';
my $string3 = eval{ $string =~ $regexp; return $string; return $string; };

print "Attempt 1: $string2\n";
print "Attempt 2: $string3\n";

exit;

Output:

Attempt 1: test.$1

Attempt 2: test.$1

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
everett.jk
  • 47
  • 1
  • 3

1 Answers1

3

As daxim comments, this answer by Ysth contains a solution. The Perl documentation says you can use the /ee regex modifier to:

Evaluate the right side as a string then eval the result.

Ysth passes '".$1"' as the right-hand side of the replacement regex. The /ee modifier first evaluates this string to ".$1". After that, eval replaces $1 with the first capture group.

Working example:

my $string = 'test-txt';
my $regexp_m = '-(\S+)$';
my $regexp_r = '".$1"';      # Note the double quotes, so it's a string in a string
$string =~ s/$regexp_m/$regexp_r/ee;
print "$string\n";
Community
  • 1
  • 1
Andomar
  • 232,371
  • 49
  • 380
  • 404