http://qs1969.pair.com?node_id=287739

asarih has asked for the wisdom of the Perl Monks concerning the following question:

While I was looking at regex to reverse string, I thought about re-inventing the reverse function with regex only. So I wrote routine:
sub rev ($) { $_ = shift; s/^(.)(.*)$/swap($2)."$1"/e if (length>1); # print "in swap: $_\n"; return $_; }
This does not work. For instance, if I feed asdfghjkl;', I get back ';;lkjhgfds. It appears to me $1 and $2 are overwritten at each level of recusion, although these should be localized. Am I missing something here?

Update: I meant to type:

sub rev ($) { $_ = shift; s/^(.)(.*)$/rev($2)."$1"/e if (length>1); # print "in rev: $_\n"; return $_; }

Update at author's req. - dvergin 2003-08-31

Replies are listed 'Best First'.
Re: Recursion and scoping of $1, $2 and friends
by broquaint (Abbot) on Aug 29, 2003 at 16:16 UTC
Re: Recursion and scoping of $1, $2 and friends
by diotalevi (Canon) on Aug 29, 2003 at 16:22 UTC