in reply to Perl Help

(For coursework) I've got to write a script which counts certain characters within a text file. I'm looking for hyphens, open and closed brackets, full stops and commas. I know how to read a file line by line. I was going to write a regular expression to scan each line, and increment a variable by one for each instance of the character found. Is there a better method for doing this?

Replies are listed 'Best First'.
Re^2: Perl Help
by moritz (Cardinal) on Jan 22, 2008 at 11:45 UTC
    Regexes aren't good for counting anything. (Yes, there are regex hacks that count things, but we leave that aside for a moment...)

    You should traverse your lines char by char and then check (perhaps with a regex, or with a hash lookup) if the char is interesting to you.

Re^2: Perl Help
by lidden (Curate) on Jan 22, 2008 at 11:57 UTC
    You want something like this:
    my %hist; while(<$fh>){ ++$hist{ $_ } for split //; } for(sort{ $hist{ $b } <=> $hist{ $a } } keys %hist){ print "'$_' => $hist{ $_ }\n"; }
    but you need to filter out the chars you don't want.