perlint has asked for the wisdom of the Perl Monks concerning the following question:

Hi, i have a need to change matches from a regex, to be changed on the fly, in the replace section. based on a suggestion from the chatterbox, I tried something like : $mystring="CONTENT- TYPE"; $mystring=~s/(.*)/{my $foo= $1; s\/\\n\/ \/; "$1"}/e; This lead to error message: Use of uninitialized value in string at ./test3.pl line 5. for my realuse, the $mystring is an entire file slurped in after changing the \n delimiter, and there may be multiple places that I get matches in the string. I need to remove the \n only for some of the matches. thanks for your help!
  • Comment on Having trouble with changing $1 of a regex

Replies are listed 'Best First'.
Re: Having trouble with changing $1 of a regex
by jethro (Monsignor) on Feb 11, 2010 at 00:10 UTC

    First of all: please use code tags around code samples, it is a wonder that your code is actually displayed correctly.

    The following is at least working code, I'm not sure that it does anything you wanted. I changed the to-be-substituted character to something more visible

    perl -e '$mystring="CONTENT- TYPE\n"; $mystring=~s/(.*)/{my $foo= $1; +$foo=~s\/N\/ \/; "$foo"}/e; print $mystring;' #prints CO TENT- TYPE

    Note that to substitute \n in this example you would have to make sure that the '.' pattern recognises \n with a regex switch 's':

    perl -e '$mystring="CONTENT- TYPE\n"; $mystring=~s/(.*)/{my $foo= $1; +$foo=~s\/\n\/ \/; "$foo"}/se; print $mystring;'
Re: Having trouble with changing $1 of a regex
by 7stud (Deacon) on Feb 11, 2010 at 01:23 UTC
    Hi, i have a need to change matches from a regex, to be changed on the fly, in the replace section.

    That is as clear as mud.

    use strict; use warnings; use 5.010; my $string = 'a6a'; my $new_val = 9; $string =~ s/(\d+)/ $1 + $new_val /e; say $string; --output:-- a15a $string =~ s/(\d+)/ "hello$1world" /e; say $string; --output:-- ahello15worlda $string = 'aXXXa'; $string =~ s/(XXX)/ my $x = $1; #$1 is read only, so can't use s/// on it $x =~ s{X}{Y}g; #use a unique delimiter so no conflict $x #previous line returns # of substitutions /e; say $string; --output:-- aYYYa