Joey Joey -3 years ago 112
Perl Question

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

my $var= "File/";
$var=~ /\w/;
print "$var";


The expected outcome is File but it doest work.

Answer Source

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";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download