Search code examples
regexstringperlreplacesubroutine

Unable to replace a string via regex through a subroutine


I am trying to replace square brackets in a string with an empty string. which means if a string is [SECTION], I want to convert it to SECTION.

I have tried this and it works,

my $sectionName =~ tr/[]//d;
print "$sectionName\n";

However, when I tried to create a general subroutine for replacing strings, it didn't work out. Here's what I tried,

sub strReplace
{
    my $string = shift;
    my $target = shift;     
    my $replacement = shift;

    $target = quotemeta $target;
    $replacement = quotemeta $replacement;

    $string =~ tr/$target/$replacement/d;

    return $string;
}

I am calling the sub like this,

# the string "[SECTION]" below is intended to be replaced by a variable
my $sectionName = strReplace("[SECTION]", "[]", "");
print "$sectionName\n";

However, instead of getting the replaced string, I am still getting the old one, i.e, [SECTION]. What am I doing wrong? (PS: Perl version 5.14.2)


Solution

  • Perl's tr/// operator does not support variables. You can find various strategies to work around this here: Perl's tr/// is not doing what I want

    To summarize, you have two main options:

    • Wrap your tr/// in an eval.
    • Convert your tr/// into a substitution using s///.