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;
In reply to Re: Replacing characters in a string
by gothic_mallard
in thread Replacing characters in a string
by natty_dread
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |