I've noticed a discrepancy between the return value behavior of substr as an lvalue and as an rvalue. Consider,

$ perl -e's//foobar/;my $foo=substr($_,2,2,"rt");print $foo,$/' ob $ perl -e's//foobar/;my $foo=substr($_,2,2)="rt"; print $foo,$/' rt $
The four argument form as rvalue evaluates to the replaced string, which is what we usually expect of it. As an lvalue, the assignments are associated right to left (as we also expect) but the substr call appears to be evaluated twice, first as an lvalue in assignment, then as an rvalue to produce the return value of that expression.

It seems that the rvalue behavior is more useful, because it allows the old data to be kept on the fly. That sort of entropy suppression is useful in functions like select.

The observed behavior may be inherent to perl's design for lvalue subs. The implementation of substr in pp.c is complicated, and I confess to not yet understanding it.

I wonder whether this is a bug, or a feature, or just a fact of life. What do you think?

After Compline,
Zaxo


In reply to An Oddity of substr by Zaxo

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.