in reply to Can you set a character in a string at a given index directly?

Hello tkguifan,

For your particular problem, substr is the best solution, as others have shown. However, you might find it useful to see how your original approach can be made to work. The missing piece of the puzzle is splice:

#! perl use strict; use warnings; while (<DATA>) { my @f = split /\s+/; my $s = insert_string(@f); printf "%9s: %s\n", $f[0], $s; } sub insert_string { my ($string, $pos, $insert) = @_; my @chars = split //, $string; splice @chars, $pos, 0, $insert; return join '', @chars; } __DATA__ advark 1 a aaacccddd 3 bbb xyz 3 w qrst 0 p

Output:

2:23 >perl 1144_SoPW.pl advark: aadvark aaacccddd: aaabbbcccddd xyz: xyzw qrst: pqrst 2:23 >

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: Can you set a character in a string at a given index directly?
by tkguifan (Scribe) on Feb 03, 2015 at 16:40 UTC
    How come the LENGTH parameter is 0? The doc says "removes the elements designated by OFFSET and LENGTH from an array". I'm removing 1 element.

      Oh, OK, I thought you were inserting a string at the given position. To replace N characters, of course you set the LENGTH parameter to N. For example, to remove 1 element, set LENGTH to 1.

      And (just for the sake of completeness), if you want to overwrite the string, you can do this:

      splice @chars, $pos, length $insert, $insert;

      which will, for example, take inputs of aaacccddd 3 bbb and thequickbrownfox 8 white, and produce outputs of aaabbbddd and thequickwhitefox, respectively.

      Hope that helps,

      Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,