How to remove a special character in a single word/variable

Home / Uncategorized / How to remove a special character in a single word/variable

Question:
my $var= "File/";
$var=~ /w/;
print "$var";

The expected outcome is File but it doest work.


Answer:
You are using the wrong operator. The match operator (m/…/ or, as you are using it, /…/) is for matching text. It tells you if your string matches the regex. It does not change the string at all.

What you want is the substitution operator (s/…/…/). That replaces the matching text with something new. In this case, you want to replace the matching string with an empty string.
my $var= "File/";
$var =~ s/w//; # // is an empty replacement string
print "$var";

But that’s still not correct as w matches any word character (alphanumerics and the underscore). What you need is W, which matches any non-word character.
my $var= "File/";
$var =~ s/W//; # // is an empty replacement string
print "$var";
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *