It was Wednesday, July 02, 2003 when Ling F. Zhang took the soap box, saying: : I use /pattern/g to progressively match a string (who : content is read from a file) : I want the cut the string off after the n-th match (if : there is no n-th match, the string is unaltered) : how can I do this without using a loop? : right now, I am doing this: : : while ($string =~ /pattern/g){ : $count++; : if ($count > $max_count){ : $string = substr($string,0,pos($string)); : last; : } : } : : I know about $', $` (and what's the third one?), but I : just can't figure out how to apply them in this case.
I'd use split in this case. my @parts = split /(pattern)/, $string, $max_count; pop @parts while @parts > ($max_count)x2; $string = join '', @parts; Here, we're split()ing on a captured pattern, but only for the maximum number of allowed segments. This will store the segments and matched split strings in @parts sequentially. Next, we take elements off the end of @parts untill the size of the list is equal to the twice the max count. the max count is doubled because we've also stored the delimiters from the split. Finally, we put the string back together. Casey West -- Shooting yourself in the foot with AIX You can shoot yourself in the foot with either a .38 or a .45. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]