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

In the following code I am trying to substitute Fred for Barney, then capitalize Barney and then output it to screen. I can do the initial substitution but when I add a second substitution the output isn't what I want.

#! /usr/bin/perl use v5.14; use warnings; $_ = "He's out bowling with Fred tonight."; s/Fred/Barney/; s/with (\w+)/against $1's team/; #This is the line of code that screws up ouptut s/$1/\U$1/gi; print "$_\n";

Replies are listed 'Best First'.
Re: Having issues with substitutions
by choroba (Cardinal) on Feb 05, 2019 at 17:57 UTC
    Successful matching resets the $1, even if there's nothing to capture. Therefore, $1 is Barney in the pattern, but it's empty in the replacement part, because the pattern ($1) doesn't capture anything.

    To make the captured string survive a match, assign it to a normal non-magical variable:

    my $who = $1; s/$who/\U$who/gi;
    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
Re: Having issues with substitutions
by Your Mother (Archbishop) on Feb 05, 2019 at 18:03 UTC

    choroba is always right. Here's more to consider–

    use v5.14; { local $_ = "He's out bowling with Fred tonight."; s/Fred/Barney/; s/with (\w+)/against \U$1\E's team/; say; }

    local and a scope block to protect $_. \U\E to uppercase and end. You could also do raw Perl in the right side of the s///e if you include the e for execute flag. say by itself because $_ is implied.