#!/usr/bin/perl
use strict;
use warnings;
my $a = '2323jjf ("$("&&"&$__\\/';
my $b = $a;
$a =~ s/\W//g;
$a =~ s/_//g;
$b =~ s/\W|_//g;
print "a = $a\n";
print "b = $b\n";
__END__
Or, in one line:
perl -pe 's/\W|_//g;'
| [reply] [Watch: Dir/Any] [d/l] [select] |
Or, in the sense of TMTOWTDI:
s/[\W_]//g
| [reply] [Watch: Dir/Any] [d/l] |
How can a "." character be allowed in the string.
| [reply] [Watch: Dir/Any] |
#!/usr/bin/perl
use strict;
use warnings;
my $a = my $b = my $c = join '', map(chr, 32 .. 126);
print "a = $a\n";
$a =~ s/\W//g;
$a =~ s/_//g;
$b =~ s/\W|_//g;
# allow letters, numbers, and dots
$c =~ s/[^a-z0-9.]//gi;
print "a = $a\n";
print "b = $b\n";
print "c = $c\n";
__END__
You should take a look at perlre when you get a chance. | [reply] [Watch: Dir/Any] [d/l] |
You want the translation operator:
$a =~ tr/\W_//g;
or you can also use the substitution operator but specifying a choice:
UPDATE to CODE: (opps)
$a =~ s/(\W|_)//g;
UPDATE: It might also be worth your while to read the perlop documentation
| [reply] [Watch: Dir/Any] [d/l] [select] |
$string =~ tr/a-zA-Z0-9.//cd;
This says to take the complement of the list created by the ranges a-z, A-Z, and 0-9, and delete anything not found among that range. Note, I didn't specifically deal with the underscore character, because with this method, the fact that I didn't include it is enough to get it deleted. Think of the list of things on the left of the tr/// operator as the list of what to keep, because we used the /c modifier. Everything else gets deleted, because we used the /d modifier.
Updated: Added the '.' character to the "keep these" character list to accommodate the fact tht the OP revised his question later in the thread asking to also preserve the dot character.
| [reply] [Watch: Dir/Any] [d/l] [select] |
This is what charclasses are for.
s/[\W_]//g
Read more about them in perlrequick, perlretut, perlre, and perlreref (at for instance www.perldoc.com).
(Using alternation for this is really awful and not just style-wise.)
ihb
| [reply] [Watch: Dir/Any] [d/l] [select] |