-2

Need to count the number of "$0.00" in a string. I'm using:

my $zeroDollarCount = ("\Q$menu\E" =~ tr/\$0\.00//);

but it doesn't work. The issue is the $ sign is throwing the regex off. It works if I just want to count the number of $, but fails to find $0.00.

How is this a duplicate? Your solution does not address dollar sign which is an issue for me.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Mehdi
  • 772
  • 7
  • 16

1 Answers1

3

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.

simbabque
  • 53,749
  • 8
  • 73
  • 136