in reply to Confused by RegEx count

If the character is constant, the following is best:

my $count = $str =~ tr/y//;

Can anyone help me understand what's going on here?

Certainly. In the general case, Perl's tr operator transliterates all occurrences of the characters found, returning the number of characters replaced or deleted (for example, $str =~ tr/y/z/ changes all y characters in $str to z, returning the number of changes made). In the special case of an empty replacement list, as in your $str =~ tr/y// above, this operator does not change the string, it simply returns the number of matching characters found, in this case the number of y characters in the string.

Note that the tr operator further supports various options, such as c to complement the search list, and that y is a synonym for tr (added to entice diehard sed users to Perl) ... so instead of $str =~ tr/y// you could equivalently write $str =~ y/y// to count the number of y characters in $str ... finally giving us enough background to understand Abigail's famous length horror:

y///c

which gives the same result as the prosaic length function, but is one character shorter. :-)

👁️🍾👍🦟