my $str = "(foo + bar)\n(baz * quux)\n"; # opening and closing parens and space => underscore $str =~ tr/() /_/; # newline => space $str =~ tr/\n/ /; print "<<$str>>\n"; #### <<_foo_+_bar_ _baz_*_quux_ >>