I have dynamically generated strings like @#@!efq@!#!
, and I want to remove specific characters from the string using Perl.
Currently I am doing something this (replacing the characters with nothing):
$varTemp =~ s/['\$','\#','\@','\~','\!','\&','\*','\(','\)','\[','\]','\;','\.','\,','\:','\?','\^',' ', '\`','\\','\/']//g;
Is there a better way of doing this? I am fooking for something clean.
Overview. We can use the chop() method to remove the last character of a string in Perl. This method removes the last character present in a string. It returns the character that is removed from the string, as the return value.
Python Remove Character from String using replace() We can use string replace() function to replace a character with a new character. If we provide an empty string as the second argument, then the character will get removed from the string.
The operator =~ associates the string with the regex match and produces a true value if the regex matched, or false if the regex did not match. In our case, World matches the second word in "Hello World" , so the expression is true.
You've misunderstood how character classes are used:
$varTemp =~ s/[\$#@~!&*()\[\];.,:?^ `\\\/]+//g;
does the same as your regex (assuming you didn't mean to remove '
characters from your strings).
Edit: The +
allows several of those "special characters" to match at once, so it should also be faster.
You could use the tr
instead:
$p =~ tr/fo//d;
will delete every f and every o from $p
. In your case it should be:
$p =~ tr/\$#@~!&*()[];.,:?^ `\\\///d
See Perl's tr documentation.
tr/SEARCHLIST/REPLACEMENTLIST/cdsr
Transliterates all occurrences of the characters found (or not found if the
/c
modifier is specified) in the search list with the positionally corresponding character in the replacement list, possibly deleting some, depending on the modifiers specified.[…]
If the
/d
modifier is specified, any characters specified by SEARCHLIST not found in REPLACEMENTLIST are deleted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With