Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: Recursive substitution

by bobf (Monsignor)
on Nov 10, 2009 at 04:27 UTC ( #806118=note: print w/replies, xml ) Need Help??

in reply to Recursive substitution

I like to take a very simple approach to such things, since the tricky methods usually confuse me when I come back to it 6 months later and have to modify it somehow. :-)

my $s = 'ab'; my $pat = qr/^(a{1,3})(?=b)/; while( $s =~ m/$pat/ ) { $s =~ s/$pat/$1a/g; }

Or, if you prefer more of the 1-liner feel:

my $s = 'ab'; my $pat = qr/^(a{1,3})(?=b)/; do{ $s =~ s/$pat/$1a/g } while $s =~ m/$pat/;

I'm sure it is possible to do this in the regex itself (probably with /e). I'm sure other monks will enlighten both of us.

Update: I changed approaches mid-code and forgot to remove the superfluous m//. These solutions are not very perlish.

Replies are listed 'Best First'.
Re^2: Recursive substitution
by JadeNB (Chaplain) on Nov 10, 2009 at 04:32 UTC

    Thanks very much. I realised shortly after posting that I hadn't explained why I didn't want the most natural answer (current explanation: because I don't, that's why), but didn't update my post in time.

    By the way, I think that s/$pat/$sub/ is (effectively) a no-op unless m/$pat/, so I think that it's redundant to do a separate m/$pat/ check.

      it's redundant to do a separate m/$pat/ check
      You are absolutely correct, of course. I started playing with patterns that would have required the extra check (because the ones used in s/// and m// were different), but I failed to remove the extra code after changing my approach. I added a note to my original reply but left the crufty code to avoid confusing future readers of this thread.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://806118]
and monks are getting baked in the sun...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2017-02-27 04:30 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (376 votes). Check out past polls.