in reply to How do I cut single characters out of a string

I'm surprised that nobody has mentioned that substr returns an lvalue. In other words, you can assign to it.

my $string = 'mystring123456'; substr($string, 8, 1) = ''; print "$string\n";

Replies are listed 'Best First'.
Re^2: How do I cut single characters out of a string
by johngg (Canon) on Jan 15, 2012 at 12:22 UTC

    Way back in the early days of Perl 5 substr didn't have the facility to supply a fourth argument so assigning to it as you describe was the only way to go. The advantage of using the 4-arg form to replace text is that what has been replaced is returned. Thus you can chain substrs together to move text around.

    knoppix@Microknoppix:~$ perl -E ' > $str = q{abcdefghijk}; > say $str; > substr $str, 5, 2, substr $str, 3, 2, substr $str, 5, 2; > say $str;' abcdefghijk abcfgdehijk knoppix@Microknoppix:~$ perl -E '

    Of course, that particular example can be done more simply with a regex substitution but it can be a useful technique sometimes.

    knoppix@Microknoppix:~$ perl -E ' > $str = q{abcdefghijk}; > say $str; > $str =~ s{^...\K(..)(..)}{$2$1}; > say $str;' abcdefghijk abcfgdehijk knoppix@Microknoppix:~$

    I hope this is of interest.

    Cheers,

    JohnGG

      substr $str, 5, 2, substr $str, 3, 2, substr $str, 5, 2;

      I'll have to remember that next time I'm entering an obfuscated code contest.

Re^2: How do I cut single characters out of a string
by JavaFan (Canon) on Jan 15, 2012 at 02:44 UTC
    Noone has mentioned that, but already 2 people before you used 4-arg substr, which in this case does the same thing.