From the docs:
You can use the substr() function as an lvalue, in which case EXPR must itself be an lvalue. If you assign something shorter than LENGTH, the string will shrink, and if you assign something longer than LENGTH, the string will grow to accommodate it.

Essentially when using substr as an lvalue it remembers the offset and length into which the rvalue will be substituted. As you surmised, the length is updated to the length of the substitution in each case. This is natural and means that each successive substitution will fully replace the previous one.

And this is what we see in each of the cases you give in your example.:

$x = '1234'; for (substr($x,1,2)) { # lvalue offset and length start at (1 +,2) $_ = 'a'; print $x,"\n"; # becomes (1,1) -- prints 1a4, $_ = 'xyz'; print $x,"\n"; # becomes (1,3) -- prints 1xyz4 $x = '56789'; # no change (1,3) $_ = 'pq'; print $x,"\n"; # becomes (1,2) after pq is subbed int +o (1,3) -- prints 5pq9 }

In reply to Re: substr question by Loops
in thread substr question by lightoverhead

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.