in reply to brackets help

I'm sure it can be written better and I haven't tested this...
my $string = "Hello ( World )."; $string =~ s/\(\s*//g; # remove opening bracket followed by spaces $string =~ s/\s*\)//g; # remove closing bracket preceded by space $string =~ s/\s/_/g; # replace spaces still left with underscores $string =~ s/\.$//; # remove ending period also
Hope that helps...

Replies are listed 'Best First'.
Re^2: brackets help
by eibwen (Friar) on May 10, 2005 at 04:14 UTC

    Presuming any non-word character should be replaced with an underscore:

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

    Note that if you wanted to replace strings containing multiple sequential _, you'd have to change \W to the appropriate character class.