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

I have a string, say $str
I want to remove the dash '-' from inside the string if it exists

So, if the string is "123-4567", I want it to become "1234567"

Any help?

Replies are listed 'Best First'.
Re: removing a character from a string
by Sifmole (Chaplain) on Jun 18, 2002 at 19:56 UTC
    Or if you are truly only looking to get rid of "-":
    my $foo = '123-4567'; $foo =~ tr/-//d; # tr is specifically for the replacement # of single characters, the "d" tells it # to remove any characters for which # is no translation provided. print $foo;
Re: removing a character from a string
by kvale (Monsignor) on Jun 18, 2002 at 19:44 UTC
    A simple way to do this is to use the substitution operator:
    $x = "123-4567"; $x =~ s/-//g;
    More generally, to remove all nondigit characters, use
    $x =~ s/\D//g;

    -Mark
Re: removing a character from a string
by mrbbking (Hermit) on Jun 18, 2002 at 19:49 UTC
    Do like this:
    my $string = '123-4567'; $string =~ s/-//g; print $string;
    s/<search>/<replace>/g; # the 'g' replaces every occurrence of <search>, not just the first.

    Update: This'll work, too:

    my $i='123-4567'; my $j; while( length($i) ){ $j .= chop( $i ); chop $j if substr( $j, -1 ) eq '-'; } print reverse split //, $j;
      Thanks :D