Search code examples
perlsubstr

removing character using substr in perl


I'm trying to remove two character from the string

This is what you have

using

substr ($string, 5, 2) = "";

The two characters are getting removed, but one extra space is left behind. I obtain

This  what you have

but I desire to get

This what you have

Can anyone help me to get rid of that space?


Solution

  • A string, like an array, starts at position 0:

    say '012345679';
    my $str = "This is what you have";
    say $str;
    
    --output:--
    012345679
    This is what you have
    

    To remove 'is' and the space preceding 'is', you need to remove positions 4, 5, 6:

    012345679
    This is what you have
        ^^^
        |||
    

    ...which you can do like this:

    say '012345679';
    my $str = "This is what you have";
    say $str;
    
    substr($str, 4, 3) = "";
    say $str;
    
    --output:--
    012345679
    This is what you have
    This what you have
    

    Alternatively, you can remove 'is' and the space after 'is' by removing positions 5, 6, 7:

    012345679
    This is what you have
         ^^^
         |||
    

    ...like this:

    say '012345679';
    my $str = "This is what you have";
    say $str;
    
    substr($str, 5, 3) = "";
    say $str;
    
    --output:--
    012345679
    This is what you have
    This what you have
    

    However, in perl most people use s/// (the substitution operator) for making substitutions:

    s/find me/replace with me/
    

    So, you can do this:

    my $str = "This is what you have"; 
    say $str;
    
    $str =~ s/\bis\b //;  # \b means 'word boundary'
    say $str;
    
    --output:--
    012345679
    This is what you have
    This what you have
    

    perl programmers are lazy, and counting positions is too hard. You do need to know regexes for most situations.

    If you want to remove all occurrences of 'is ' in a string, then you can add the 'g' (global) flag:

    my $str = "This is what you have, but his hat is black isn't it?";
    say $str;
    
    $str =~ s/\bis\b //g;
    say $str;
    
    --output:--
    This is what you have, but his hat is black isn't it?
    This what you have, but his hat black isn't it?
      ^                      ^            ^
      |                      |            |
        skips 'is' embedded in other words