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

How do i remove underscores.


for eg. i have a $txt = "This_is_a_song_.mp3";

I want it to be "This_is_a_song.mp3"; How do i remove the last underscore.

Thanks

Replies are listed 'Best First'.
Re: Removing underscores.
by gellyfish (Monsignor) on May 06, 2005 at 15:17 UTC

    something like:

    $text =~ s/_+\././;
    I would guess

    /J\

Re: Removing underscores.
by davidrw (Prior) on May 06, 2005 at 15:50 UTC
    As Transient said, it depends on your criteria. If it's the underscore-period combo you need taken care of, then gellyfish's solution should suffice. If it's just the last underscore no matter what, then a greedy regex like this could work:
    my $txt = "This_has_under_scores.mp3"; $txt =~ s/(.+)_/$1/; print $txt; # "This_has_underscores.mp3";
    Update: ... or non-greedy from the other end:
    $text =~ s/_(.*?)$/$1/;
Re: Removing underscores.
by Transient (Hermit) on May 06, 2005 at 15:19 UTC
    You have to come up with some kind of logical criteria. Why is the last underscore unacceptable? Determine that and we might able to help you. By your question above, I could simply say that if you had
    $txt = "This_is_a_song_.mp3";
    and you want it to be "This_is_a_song.mp3". Do this:
    $txt = "This_is_a_song.mp3";
    but that's probably not very helpful.
Re: Removing underscores.
by jeffa (Bishop) on May 06, 2005 at 17:01 UTC

    Try a segexer (reverse regex)

    my $str = 'This_is_a_song_.mp3'; $str = reverse $str; $str =~ s/_//; $str = reverse $str;

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: Removing underscores.
by samizdat (Vicar) on May 06, 2005 at 15:57 UTC
    Your question is not clear.

    I could say
    $txt =~ s/_+//g; $txt =~ s/_+\././;
    And they'd both remove the one you want gone... but react differently in other cases.
Re: Removing underscores.
by Anonymous Monk on May 06, 2005 at 17:46 UTC
    you could do $txt= join ('', ($txt =~ /(.*)_(\..*)/)) || $txt;
Re: Removing underscores.
by TedPride (Priest) on May 06, 2005 at 22:54 UTC
    $txt = "This_is_a_song_.mp3"; substr($txt, rindex($txt, '_'), 1) = ''; print $txt;
    You could also do it with a greedy regex, as stated above:
    $txt = "This_is_a_song_.mp3"; $txt =~ s/(.*)_/$1/; print $txt;