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

Relative newbie here...I'm trying to find a way to replace the 4th & 5th characters in a string with certaing letters. For instance I'd like to take the word nodes0005 with nodAB0005. I'd like to insert the chars 'es' in the original word with 'AB'.

Wondering if I need to read the individual letters into an array?
Respectfully....

Replies are listed 'Best First'.
Re: Replacing characters in a string
by kutsu (Priest) on Oct 04, 2004 at 14:12 UTC

    If your the characters are always the 4th & 5th chars, you might want to look at substr, if they are based on a pattern look at regexes.

    "Cogito cogito ergo cogito sum - I think that I think, therefore I think that I am." Ambrose Bierce

Re: Replacing characters in a string
by borisz (Canon) on Oct 04, 2004 at 14:33 UTC
Re: Replacing characters in a string
by sweetblood (Prior) on Oct 04, 2004 at 14:20 UTC
Re: Replacing characters in a string
by gothic_mallard (Pilgrim) on Oct 04, 2004 at 14:36 UTC

    Probably the easiest thing to do given your example is use a substring with substr()

    my $str = 'nodes0005'; substr($str,3,2,'AB'); print $str; # .. produces: nodAB005 # as required.

    Here we're replacing 2 chars from position 3 (remember that the numbering starts at 0 so that 0=n, 1=o, 3=d etc) with the string 'AB'. (see the perl manual for full details on using substr())

    It is possible to use a regex but that would probably be over-complicating matters for such a simple case.

    Update: You don't need to go as far as reading the string into an array, but just for fun:

    my $str = 'nodes0005'; my @chars = split //, $str; # Split the string into an array. my $out = ''; # Define an output string for (my $i=0; $i<@chars; $i++) { if ( $i==3 ) { $out .= 'A'; # Character 4, replace with 'A' } elsif ($i==4) { $out .= 'B'; # Character 5, replace with 'B' } else { $out .= $chars[$i]; # Neither 4 or 5 so just straight output it } } print $out;
      You don't need to go as far as reading the string into an array, but just for fun

      I wouldn't exactly call this type of text processing fun, but if you really must, the way you've shown is far more complicated than it needs to be:

      my $str = 'nodes0005'; my @chars = split //, $str; @chars[3,4] = ("A", "B"); my $out = join "", @chars;