my $s = 'Hello ( World ).'; $s =~ s/\W+/_/g; # Replace all sequences of [^a-zA-Z0-9_] with _ $s =~ s/_$//; # Remove trailing _ if present