Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: How to make only two of three substitutions?

by nothingmuch (Priest)
on Oct 15, 2002 at 21:44 UTC ( #205530=note: print w/replies, xml ) Need Help??


in reply to How to make only two of three substitutions?

Something which I believe may be of some interest to you is the \G zero width assertion.
$_ = "1/ 2/ 3/"; m{/}g; # will set pos to 2, the offset of the first '/' s{\G(.*?)/}{$1}g; # \G is like ^, but instead of matching # a line begining it matches the place # where the last /g modified regexp left # off. print;
The above code first finds a slash, and saves it's position in the lvalue acccessible by pos($_). Because the m//g is not performed in list context, the slashes are not all pushed to a list and returned. Scalar/void context m//g lets you step through the string, in an iterational fashion.
Next, the substitution is performed so that the match has to succeed \G. \G is the place where the last /g left off. /g modification on s/// substitutes everything regardless of context. The first slash found, and it's position noted, we proceed to find a minimal anything, followed by a slash. Once we find that, we replace it with the minimal anything, and remember the position. We then search onward for more slashes, until no match can be made.

This specific example is a bit flawed, because it invloves a lot of copying, in theory, and it is also not the best choice for your specific example, but I just thought it may be useful to know.
perlre contains more info.

-nuffin
zz zZ Z Z #!perl

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://205530]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (6)
As of 2019-10-20 21:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?