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

I was about to comment (sarcastically) on Removing underscores. when I got confused by somehting, so I am here seeking knowledge from a monk wiser than I. I tried this:

perl -e 'my $str = "This_is_a_song_.mp3"; substr($str, 14, 1, ''); pri +nt $str."\n";'

and got:

This_is_a_song_.mp3

I would have expected substr to remove the last underscore (the character at offset 14). However it appears that because my replacement had a length of zero, perl acted as though I hadn't given it a replacement. Does the "REPLACEMENT" argument to substr need to have length in order to be considered valid?

substr

Update: My ignorance has been discovered. Thank you all for sharing your knowledge


They say that time changes things, but you actually have to change them yourself.

—Andy Warhol

Replies are listed 'Best First'.
Re: Using substr to remove characters
by Zaxo (Archbishop) on May 06, 2005 at 18:34 UTC

    The shell is misinterpreting your command line because of interior single quotes, dropping the fourth argument.

    $ perl -e 'my $str = "This_is_a_song_.mp3"; substr($str, 14, 1, ""); p +rint $str."\n";' This_is_a_song.mp3 $

    After Compline,
    Zaxo

Re: Using substr to remove characters
by bmann (Priest) on May 06, 2005 at 18:33 UTC
    It's a shell quoting issue, not a substr issue. Change the single quotes around the empty string to double quotes, it'll work fine.
    $ perl -e 'my $str = "This_is_a_song_.mp3"; substr($str, 14, 1, ""); p +rint $str."\n";' This_is_a_song.mp3
Re: Using substr to remove characters
by Transient (Hermit) on May 06, 2005 at 18:32 UTC
    perl -e 'my $str = "This_is_a_song_.mp3"; substr($str, 14,1)=""; print + $str."\n";'
    If you want to modify it

    Update: As bmann and Zaxo correctly surmise, this is a shell issue, not a subtr issue. However, the above is another way to modify it :D
Re: Using substr to remove characters
by thcsoft (Monk) on May 07, 2005 at 09:26 UTC
    after all, i still don't understand, why you're usiińg substr() at all - instead of a regex:
    #!/usr/bin/perl -w use strict; my $str = "This_is_a_song_.mp3"; $str =~ s/_(\.mp3)$/$1/g; print "$str\n";
    another way might be:
    use strict; my $str = "This_is_a_song_.mp3"; my ($pre, $post) = split /\./, $str; chop $pre; $str = "$pre.$post"; print "$str\n";
    ... and so on, and so on... :D

    language is a virus from outer space.

      i still don't understand, why you're usiińg substr() at all - instead of a regex

      Speed

      $str =~ s/_(\.mp3)$/$1/g; # Or Much faster with the same result: substr($str, -5, 1, "") if(substr($str, -5, 1) eq '_');

      If you do not need the power of metacharacters which a regex offers, don't use a regex. Using a regex for this opperation is like using a sledge hammer to pound in a small nail.


      They say that time changes things, but you actually have to change them yourself.

      —Andy Warhol