You are using the transliteration operator tr///
. That doesn't have anything to do with a pattern. You need the match operator m//
instead. And because you want it to find all occurances of the pattern, use the /g
modifier.
my $count = () = $menu =~ m/\$0\.00/g;
If we run this program, the output is 2.
use strict;
use warnings;
my $menu = '$0.00 and $0.00';
my $count = () = $menu =~ m/\$0\.00/g;
print $count;
Now lets take a look at what is going on. First, the pattern of the match.
/\$0\.00/
This is fairly straight-forward. There is a literal $
, which we need to escape with a backslash \
. The zero is followed by a literal dot .
, which again we need to escape, because like the $
it has special meanings in regular expressions.
my $count = () = $menu =~ m/\$0\.00/g;
This whole line looks weird. We can break it up into a few lines to make it more readable.
my @matches = ( $menu =~ m/\$0\.00/g );
my $count = scalar @matches;
We need the /g
switch on the regular expression match to make it match all occurrences. In list context, the match operation returns all matches (which will be the string "$0.00"
a number of times). Because we want the count, we then force that into scalar
context, which gives us the number of elements. That can be shortened to one line by the idiom shown above.