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

hi
i want to remove some characters from a string but the characters are in a variable wich may have its value from a GUI TextBox, my program is:
use strict; use warnings; my $string = "aabbzzb"; my $oldchars = "ab"; my $newchars = "xx"; $_ = $string; #replace the chars by "x" char. eval "tr/$oldchars/$newchars/, 1" or die $@; $string = $_; #then delete the 'x' char. $string =~ tr/x//d; print $string; #will print zz
can you suggest a best methods!.
thanks
  • Comment on deleting characters from a string but the characters are in a variable
  • Download Code

Replies are listed 'Best First'.
Re: deleting characters from a string but the characters are in a variable
by moritz (Cardinal) on Nov 12, 2008 at 11:07 UTC
    If you just want to delete them:
    $string =~ s/[$oldchars]//g

    If you want to replace them:

    eval "\$string =~ tr/$oldchars/$newchars/"

    In both cases you might need to escape something if there are meta characters, for example with quotemeta for the regex.

Re: deleting characters from a string but the characters are in a variable
by GrandFather (Saint) on Nov 12, 2008 at 11:07 UTC

    Well, you can simplify the translate to a single line:

    use strict; use warnings; my $string = "aabbzzb"; my $oldchars = "//; print `dir *.*`; \\\$string =~ tr/"; eval "\$string =~ tr/$oldchars//d"; print $string; #will print zz

    but as you may notice from the sample $oldChars string a savy user could take advantage of the string eval to do interesting stuff.

    Probably you would be better to use a regex:

    $string =~ s/[$oldchars]//g;

    which at least is a little harder to subvert. Better still would be to sanitise $oldchars before it is used in the regex, but how you do that depends a great deal on what is appropriate in oldChars.


    Perl reduces RSI - it saves typing
Re: deleting characters from a string but the characters are in a variable
by Anonymous Monk on Nov 12, 2008 at 10:59 UTC
    You don't need to use eval/tr, just use s///
Re: deleting characters from a string but the characters are in a variable
by ww (Archbishop) on Nov 12, 2008 at 12:19 UTC
    Is your question re an appropriate method of deleting "some characters" or re getting those chars "from a GUI TextBox" to your script?
      it is about an appropriate method of deleting "some characters" referenced to by a variable, the presented answers are excellent
      thanks for all