[Boston.pm] function that takes two arguments and passes them into s///

"Greg London" <email-2Ro/Dj86MvDSUeElwK9/[email protected]> Wed, 30 Jan 2019 13:36:14 -0500
Newsgroups gmane.comp.lang.perl.perl-mongers.boston
Message-ID <[email protected]>
Tried to boil this down to the smallest testcase i could come up with.

I have a function that wraps a s/// substitution.
Callers pass in the pattern and the replacement string.
There's a bunch of other stuff going on that is why the
function exists, but isn't why it isn't working.

It's not working when I try pass in $1 as a substitution string.
Cant get it to eval 'PREFIX_$1' inside the s/// piece.

i've tried s///e and s///ee and neither work.
I've tried qq()'ing the text, tryign to turn it into an expression, etc.
Everything I've tried, I get one of two things in the output:
Either the output has literally PREFIX_$1 in the result
or it completely removes teh previx_nn from the result.

I've used eval() on '$var' in other settings and it works.
But cant seem to get it to work in the case of the replacement
string in a s/// substitution.

Thoughts?

I'm using perl 5.8, if it matters.

Here's the test code:


#!/usr/bin/perl

use warnings;
use strict;

#---------------------------------------
# modules and other library code
#---------------------------------------

my $content =<<'CONTENT';
some prefix string
HERE: prefix_01
post prefix stuff
CONTENT


sub cleanup{
	my($oldtext, $newtext)=@_;
	my $original=$content;
	my $modified=$content;
	my $changed_flag=0;

	if($modified =~ s/$oldtext/$newtext/ge  ){
		$changed_flag=1;
	}

	print "\n\n################################################\n";
	print "oldtext is '$oldtext'\nnewtext is '$newtext'\noriginal:
\n$original\n";
	print "modified: \n$modified\nchange_flag is $changed_flag\n";

}

#---------------------------------------
# user code
#---------------------------------------

# straightforward pattern with no capture: works
cleanup('prefix','PREFIX');

# using capture parens and $1: does not work
cleanup('prefix_(\w+)', 'PREFIX_$1');