http://www.perlmonks.org?node_id=16931

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

Example :
In the string "     " (5 chars long), add "A" at character 3 and "B" at character 2 to result in " BA  ".

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I insert characters at certain positions in a string?
by Anonymous Monk on Sep 16, 2003 at 22:28 UTC
    If you do not want to replace the character you can set the substring length to zero.
    my $padded = 'ABCDEFG'; substr($padded, 2, 0) = '1'; substr($padded, 1, 0) = '2';
    This will result in 'A2B1CDEFG'
Re: How do I insert characters at certain positions in a string?
by mdillon (Priest) on Jun 07, 2000 at 22:47 UTC
    my $padded = ' ' x 5; substr($padded, 2, 1) = 'A'; substr($padded, 1, 1) = 'B';
    Will result in: ' BA  '