KStowe has asked for the wisdom of the Perl Monks concerning the following question:

Morning ladies and gents.
What is the best way to keep a running tally of the times I find a ";" in a file?

I am inputting a list of text files, (via a single text file) then sticking the list into an array, from there I need to go into each one and count the number of times we get ";"...I know I can use $count = ($string =~ tr/X//); to count the number of times it appears in one file, but how do I keep this a total of all files until I've checked all the files? Hope this makes sense, it's still early and I haven't had enough coffee! Thanks.
KStowe

Replies are listed 'Best First'.
Re: Counting within numerous files?
by japhy (Canon) on Jul 19, 2001 at 19:06 UTC
    Just do $count += $string =~ tr/;//; instead.

    _____________________________________________________
    Jeff japhy Pinyan: Perl, regex, and perl hacker.
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Re: Counting within numerous files?
by dvergin (Monsignor) on Jul 19, 2001 at 19:12 UTC
    Your problem as you state it is not how to count the occurances of a character. It is how to cycle through all the files in your list and keep track of that accumulating count.

    Here's a bit of sample code that should help:

    use strict; # these are sample files from my test directory my @files = qw(testhere.pl closure.pl hello.pl); my $semi_count; foreach my $file (@files) { open FILE, $file or die "Can't open $file: $!\n"; $semi_count += tr /;// for <FILE>; close FILE; } print $semi_count;

      Another alternative would be the little-used trick of assigning to @ARGV. You can then read each line of all of the files in turn using the diamond operator, <>.

      @ARGV = qw(testhere.pl closure.pl hello.pl); my $semi_count; $semi_count += tr/;// while <>;

      Update: Less patronising, more informative.

      --
      <http://www.dave.org.uk>

      Perl Training in the UK <http://www.iterative-software.com>

Re: Counting within numerous files?
by stefan k (Curate) on Jul 19, 2001 at 19:11 UTC
    You might be interested in the thread tr/// statement where some nice solutions to a very similar problem have been posted

    Regards... Stefan