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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.