Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi i have a string like
Hello ( World ).

How do i remove the whitespaces and brackets to get
Hello_World

Replies are listed 'Best First'.
Re: brackets help
by rupesh (Hermit) on May 10, 2005 at 04:09 UTC

    $_='Hello ( World )'; print "$1_$2" if /(\w+) \( (\w+) \)/; ^D Hello_World
    Cheers,
    Rupesh.
      Interesting. What is the ^d for?

      The ^d line was a syntax error on my system, winxp activestate.

        What is the ^d for?
        It's shorthand for "Control-d", or unix End-of-file character. rupesh was using perl as an interactive processor. (Type "perl" at a command prompt, enter the code, then press "Control-d"). I think windows might use CTRL-z or somesuch, but I don't actually.... care, tbh.

        davis
        Kids, you tried your hardest, and you failed miserably. The lesson is: Never try.
Re: brackets help
by webengr (Pilgrim) on May 10, 2005 at 04:46 UTC
    Essentially the same as the others, but uses 'join' and capturing parens:
    use strict; use warnings; my $string = 'Hello (World).'; print join '_', ($string =~ /(\w+)/g); Prints: Hello_World
    PCS
Re: brackets help
by tlm (Prior) on May 10, 2005 at 09:37 UTC

    I think this is a job for split+join:

    perl -le 'print join "_", split /\W+/, "Hello ( World )"' Hello_World

    the lowliest monk

Re: brackets help
by etm117 (Pilgrim) on May 10, 2005 at 04:01 UTC
    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...

      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.