http://qs321.pair.com?node_id=197779

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

OK, I'm a perl newbie, and I'm glad you folks are around.

I'd have thought this question had an easy answer, but my research just revealed nothing. Here's the issue:

Take a substitution command as follows:

$abcd =~ s/ab/cd/i;

As above, it'll match the first "ab" and change it to "cd" Easy. ok, to make it work on every instance of "ab" in the doc, change it to this by adding the "g":

$abc =~ s/ab/cd/gi;

But what if I want it to match UP TO the first 5 instances when I'm not sure how many instances are in the doc? Lets say there may be 1 or 4 or 7 or twenty instances, but in all cases I just want up to the first 5?

I've seen the following notation:

* - Match zero or more times
+ - Match one or more times
? - Match zero or one time
{X} - Match X times EXACTLY.
{X,} - Match X or more times
{X,Y} - Match X to Y times

But for example, the "match X to Y times" won't work for me if the document contains more than Y instances, and I only want the first 5. It'll only MATCH if the required ranges exist--apparently has nothing to do with the number of substitutions actually made, which will be zero if the instances don't fall within the range...

OK, once more, lest I've confused you. I want the substitution to occur only on the first 5 instances, or fewer, if fewer than 5 exist.

Surely there's an easy way to do this?