Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Recursion and scoping of $1, $2 and friends

by asarih (Hermit)
on Aug 29, 2003 at 16:11 UTC ( #287739=perlquestion: print w/replies, xml ) Need Help??

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

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://287739]
Approved by blue_cowdawg
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (5)
As of 2022-09-30 07:19 GMT
Find Nodes?
    Voting Booth?
    I prefer my indexes to start at:

    Results (125 votes). Check out past polls.