in reply to Replacing characters in a string

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;

Replies are listed 'Best First'.
Re^2: Replacing characters in a string
by revdiablo (Prior) on Oct 04, 2004 at 17:45 UTC
    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;