ssr1012 ssr1012 - 4 months ago 9
Perl Question

Find and Replace for same characters in both variables in single shot

I want to find and replace in more than one scalar variables which stored content (content will vary for each string) Hence I need to insert two lines for same replacement for both variables.

$str1=~s/\_/&underscore\;/g;
$str1=~s/\^/&carrot\;/g;

$str2=~s/\_/&underscore\;/g;
$str2=~s/\^/&carrot\;/g;


Is there any possibilities to replace in a single shot/simultaneously for all string to replace. Note that content will vary in strings. (May be my way of asking question is kid but I am doing the replacement more than 200 lines however trying to reduce the coding lines)

Answer

You can put your variables in a for loop, which will alias $_ to each of them in turn. Note that neither underscore nor semicolon need to be escaped inside a regex pattern

for ( $str1, $str2 ) {
    s/_/&underscore;/g;
    s/\^/&carrot;/g;
}

However both of those are non-standard entities. Have you declared them yourself? And you probably mean caret rather than carrot, which is a vegetable! I have seen it called ^, but I think that is also non-standard. You could always use ^ (and _ for the underscore)