Strip a set of characters from a string: Difference between revisions

Content deleted Content added
Line 476: Line 476:


=={{header|Perl}}==
=={{header|Perl}}==
Note: this example uses a regular expression character class. Certain characters, like hyphens and brackets, may need to be escaped.
Caveat: in this version hyphens in the second argument can be used to specify ranges; if you need to actually strip hyphens, make sure the hyphen is the first or last character.

<lang perl>sub stripchars {
<lang perl>sub stripchars {
my ($s, $chars) = @_;
my ($s, $chars) = @_;
Line 489: Line 488:
Sh ws soul strppr. Sh took my hrt!
Sh ws soul strppr. Sh took my hrt!
</pre>
</pre>

Another good option for stripping characters is to use the <code>tr///</code> operator. This option is very efficient when the set of characters to strip is fixed at compile time (note that hyphens also have special meaning in this case):
<lang perl>$str =~ tr/aei//d;</lang>

Since the characters used for <code>tr///</code> must be fixed at compile time, unfortunately, it requires the use of an <code>eval</code> to do this generally for any set of characters provided at runtime:
<lang perl>sub stripchars {
my ($s, $chars) = @_;
eval("\$s =~ tr/$chars//d;");
return $s;
}</lang>


=={{header|Perl 6}}==
=={{header|Perl 6}}==