P is for Practical | |
PerlMonks |
Re^2: find a string and count of its occurence in a text fileby fenLisesi (Priest) |
on Nov 14, 2007 at 12:20 UTC ( [id://650727]=note: print w/replies, xml ) | Need Help?? |
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:
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?
In Section
Seekers of Perl Wisdom
|
|