Skip to content

Instantly share code, notes, and snippets.

@rsperl
Last active August 4, 2021 20:02
Show Gist options
  • Save rsperl/e65612be6b0daae6f5dd13963ef570ea to your computer and use it in GitHub Desktop.
Save rsperl/e65612be6b0daae6f5dd13963ef570ea to your computer and use it in GitHub Desktop.
counting the number of occurrences of a string inside another string #perl
#!/usr/bin/env perl
use strict;
use Data::Dumper;
use Test::More;
diag "\n>>> Run as 'prove -v $0'<<<\n";
my $doc =<<EOF;
counting the number of occurrences of a string inside
another string
note - does not work for overlapping matches
the match returns all the matches. not very exciting
if you are searching for a particular string, but more
so if you are \$search_for is a regex.
EOF
note $doc;
my $search_for = 'abc';
my $in_str = 'abc abc def abc';
my $expected_count = 3;
my @expected_count = qw(abc abc abc);
my @got_count = $in_str =~ /$search_for/g;
diag("got array of matches: " . Dumper(\@got_count));
is_deeply(\@got_count, \@expected_count, "got array of matches of '$search_for' in '$in_str'");
$doc =<<EOF;
if you only want the count, you can apply a list
context to the match (similar to calling "scalar" on
an array)
EOF
note $doc;
my $got_count = () = $in_str =~ /$search_for/g;
is($got_count, $expected_count, "got $expected_count of matches of '$search_for' in '$in_str'");
done_testing;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment