Word boundaries help a global search count whole tokens instead of substrings.

Word Boundaries

word_boundaries.pl
use strict;
use warnings;

my $text = ;
my $count = 0;
my $last_pos = 0;

while ($text =~ /\bcat\b/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 = ;
my $count = 0;
my $last_pos = 0;

while ($text =~ /\bcat\b/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 = ;
my $count = 0;
my $last_pos = 0;

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

print "text=$text\n";
print "count=$count\n";
print "last_pos=$last_pos\n";
word-boundaries Use word boundaries when the pattern should match a token by itself and skip the same letters inside a larger word.