The g flag can find repeated matches in a string.

global match A global match keeps searching after the previous match.

Global Find

text
global_find.pl
Replay: real traced execution (multi-file project)
use strict;
use warnings;

my $text = "cat bat cat";
my $count = 0;
my $last_pos = 0;

while ($text =~ /cat/g) {
    $count = $count + 1;
    $last_pos = pos($text);
}

print "text=$text\n";
print "count=$count\n";
print "last_pos=$last_pos\n";
use strict;
use warnings;

my $text = "dog cat";
my $count = 0;
my $last_pos = 0;

while ($text =~ /cat/g) {
    $count = $count + 1;
    $last_pos = pos($text);
}

print "text=$text\n";
print "count=$count\n";
print "last_pos=$last_pos\n";
use strict;
use warnings;

my $text = "dog bird";
my $count = 0;
my $last_pos = 0;

while ($text =~ /cat/g) {
    $count = $count + 1;
    $last_pos = pos($text);
}

print "text=$text\n";
print "count=$count\n";
print "last_pos=$last_pos\n";
  1. $text ← cat bat cat, $count ← 0, $last_pos ← 0

    4my $text→ cat bat cat = "cat bat cat"; #@text="dog cat", "dog bird"5my $count→ 0 = 0;6my $last_pos→ 0 = 0;
  2. $count ← 1, $last_pos ← 3

    pass 1 of 2
    8while ($textcat bat cat =~ /cat/g) {9    $count→ 1 = $count + 1;10    $last_pos→ 3 = pos($textcat bat cat);11}
  3. $count ← 2, $last_pos ← 11

    pass 2 of 2
    8while ($textcat bat cat =~ /cat/g) {9    $count→ 2 = $count + 1;10    $last_pos→ 11 = pos($textcat bat cat);11}
  4. print "text=$text ";

    13print "text=$textcat bat cat\n";14print "count=$count2\n";15print "last_pos=$last_pos11\n";
    outputtext=cat bat cat
    count=2
    last_pos=11
  1. $text ← dog cat, $count ← 0, $last_pos ← 0

    4my $text→ dog cat = "dog cat";5my $count→ 0 = 0;6my $last_pos→ 0 = 0;
  2. $count ← 1, $last_pos ← 7

    8while ($textdog cat =~ /cat/g) {9    $count→ 1 = $count + 1;10    $last_pos→ 7 = pos($textdog cat);11}
  3. print "text=$text ";

    13print "text=$textdog cat\n";14print "count=$count1\n";15print "last_pos=$last_pos7\n";
    outputtext=dog cat
    count=1
    last_pos=7
  1. $text ← dog bird, $count ← 0, $last_pos ← 0

    4my $text→ dog bird = "dog bird";5my $count→ 0 = 0;6my $last_pos→ 0 = 0;78while ($text =~ /cat/g) {9    $count = $count + 1;10    $last_pos = pos($text);11}1213print "text=$textdog bird\n";14print "count=$count0\n";15print "last_pos=$last_pos0\n";
    outputtext=dog bird
    count=0
    last_pos=0