Alister West

home is where your code is ...

Count substrings in a string.

I can't seem to find a nice way to do this easily and simply. This could be for counting the number of *<img* tags in a html file or for counting vowels in a sentence.

What I would like is a $MATCHES_COUNT or a scalar keys %- after a match operation.

# m/../g, both need to be assigned to an array
# See:
# perldoc perldiag *Use of implicit split to @_ is deprecated*

my $string = "abcdefghijklmnopqrstuvwxyz";
my @vowels = $string =~ m/a|e|i|o|u/g;
say scalar @vowels; 

# Bad for large chunks of text.
my @splits = split m/a|e|i|o|u/, $string;
say $#splits; 

# Forcing array context
my $string = "foo Foo FOO Fos\nooF fOO\n";
my $count = () = $string =~ m/foo/ig;
say $count;

# Looping using index and substring? 
# I can't think of a simple way to do this.
By Alister West