CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Frequently Asked Questions:
How do I change the Nth occurrence of something?

 



Jasmine
Administrator

Jan 19, 2001, 2:50 PM

Post #1 of 1 (1617 views)
How do I change the Nth occurrence of something? Can't Post

(From the Perl FAQ)

How do I change the Nth occurrence of something?

You have to keep track of N yourself. For example, let's say you want to change the fifth occurrence of "whoever" or "whomever" into "whosoever" or "whomsoever", case insensitively.

Code
    $count = 0; 
s{((whom?)ever)}{
++$count == 5 # is it the 5th?
? "${2}soever" # yes, swap
: $1 # renege and leave it there
}igex;

In the more general case, you can use the /g modifier in a while loop, keeping count of matches.

Code
    $WANT = 3; 
$count = 0;
while (/(\w+)\s+fish\b/gi) {
if (++$count == $WANT) {
print "The third fish is a $1 one.\n";
# Warning: don't `last' out of this loop
}
}

That prints out: "The third fish is a red one." You can also use a repetition count and repeated pattern like this:

Code
    /(?:\w+\s+fish\s+){2}(\w+)\s+fish/i;


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives