Question

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)

Was it helpful?

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///.

OTHER TIPS

If your main case for strReplace is actually just to remove characters, I'd write a less-general-purpose sub that does that. Otherwise, a s/// conversion that can both remove and replace looks like this:

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

    my %replacement;
    @replacement{ split //, $target } = split //, $replacement;

    $string =~ s{ ([\Q$target\E]) }{ $replacement{$1} // '' }gxe;

    return $string;
}

The substitution repeatedly (because of the /g flag) looks for [\Q$target\E] (a character in a class of any the characters in $target, any special characters automatically escaped if necessary by \Q...\E), and replaces it with the value found by looking in the hash, or just removes it if it wasn't found in the hash.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top