perlfunc's entry on substr says:

If the lvalue returned by substr is used after the EXPR is changed in any way, the behaviour may not be as expected and is subject to change. This caveat includes code such as print(substr($foo,$a,$b)=$bar) or (substr($foo,$a,$b)=$bar)=$fud (where $foo is changed via the substring assignment, and then the substr is used again), or where a substr() is aliased via a foreach loop or passed as a parameter or a reference to it is taken and then the alias, parameter, or deref'd reference either is used after the original EXPR has been changed or is assigned to and then used a second time.

I had to read that last sentence several times to understand it, but I think it covers what your code does: you've taken a reference to a substr, changed the referee string, taken a reference to a substring of that referee, and changed the referee of that. Don't do that.

Here's some code that does what you want:

#!/usr/bin/perl -l use warnings; use strict; sub recurse($); sub recurse($) { my $a = $_[0]; print ">> '$a'"; $a =~ s/ ^ (.) (.+) (.) $ / join '', $1, recurse $2, $3 /ex; print "<< '$a'"; " ( $a ) "; } print "Result: ", recurse 'aaaaaaaaaa';

Markus

Update: diotalevi pointed out that my description of the problem with the OP's code was wrong. I've fixed it.


In reply to Re: Scalar refs, aliasing, and recursion weirdness. by MarkusLaker
in thread Scalar refs, aliasing, and recursion weirdness. by BrowserUk

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.