http://qs321.pair.com?node_id=428251


in reply to Scalar refs, aliasing, and recursion weirdness.

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.