So I ran a perldoc chomp and saw this (in a page that is a good read in its entirety):
If you chomp a list, each element is chomped, and the total number of characters removed is returned.
and then I ran perldoc transliterate, searched inside the page for "Transliterates" and saw these:
- Options: c => Complement the SEARCHLIST.
- It returns the number of characters replaced or deleted
I figure, @/ is an ordinary array, just like @records, say. We already have a glob, */, and we are even using its special-purpose scalar portion in this example, so why not use its array slot, too? I wondered whether I could use chomp(()=<FILE>) instead, but no, it doesn't work. The assignment to the empty list probably succeeds in executing <FILE> in list context, but then throws away the results and does not provide chomp() an lvalue to work with.
The $/ =~ y///c bit, then, counts the number of characters in $/, the input-record-separator, by replacing everything, all chars in the input-record-separator (here described as the complement of nothing) with nothing and returning the number of chars thus replaced. You could just replace that whole expression with 3 in this particular case, as that's the number of characters in "abc", the value of the input-record-separator, but the counting makes the code portable to other input-record-separators.
The program is probably memory-hungry. Although it is not in slurp mode, all the lines seem to get stored in the @/ array, before chomp(LIST) has a chance to work on them.
In any case, chomp() cuts off all trailing occurrences of "abc" in @/ and returns the number of chars it thus cut off. Dividing that by three (that is, by $/=~y///c) then gives you how many times "abc" occurs in the file.
Is that right, monks?
| [reply] [d/l] [select] |
The $/ =~ y///c bit, then, counts the number of characters in $/, the input-record-separator, by replacing everything, all chars in the input-record-separator (here described as the complement of nothing) with nothing and returning the number of chars thus replaced.
Not quite; since the REPLACEMENTLIST defaults to the (post-complementing) SEARCHLIST (except with /d), all the chars are replaced with themselves, not nothing. So $/ is unchanged. (Actually, tr aka y recognizes when it's
only being used to count and can even be used on readonly strings then.)
| [reply] [d/l] [select] |