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

Hello everyone, can someone point me in the right direction because I'm just spinning my wheels. I'm trying to read in the first user then loop through the array to count how many times it occured and then go to the next user and then loop through the array again counting that user etc... I think I'm missing a MAJOR fundamental concept here. Thanks
#!/usr/bin/perl use win32; use strict; open(FILE,"chargenode.txt") || die "user.pl can't open writing: $!"; while (<FILE>) { #chomp; my @names; my $match; my $count; my $total; my $item; my @x; my ($name) = /(\w+\d+)/; push @names, $name; # if (m/.*\Hm54/) { # $count++; # # my $total = $count + $count; # } #$count += $_ for @names; # sample input: # UserID Date # Hm54 ATHENA02 10/1/2000 # Dh60 ATHENA02 10/1/2000 # Dh60 ATHENA02 10/2/2000 # Jch6 ATHENA05 10/2/2000 # Hh24 ATHENA05 10/2/2000 # Mwm22 ATHENA03 10/2/2000 $match = "Hm54"; foreach my $user (@names) { if ($match eq $user) { push @x, $item; } foreach $item (@x) { $count++; $total = $count; print "saw $name $total times \n"; } } #foreach } #while close FILE;

Replies are listed 'Best First'.
Re: count string occurance
by rob_au (Abbot) on Jul 27, 2001 at 20:10 UTC
    You'd do better to loop through the array only once and store the count in a hash, using the username as the unique key. eg.
    #!/usr/bin/perl @array = ( "Hm54", "Dh60", "Dh60", "Be45", "Be45", "Be45" ); my (%count); $count{$_}++ foreach @array; print $_, " -> ", $count{$_}, "\n" foreach keys %count; exit 0;

     
    ... and the output ...
    Be45 -> 3 Dh60 -> 2 Hm54 -> 1

     
    Ooohhh, Rob no beer function well without!
      thanks rob, I've seen matches done this way, but what if there are 250 users and the users change often? Isn't there a way to populate that @array, instead of "hard coding" them in? ******** ducks the tomatos *********
        In that case, you'd read the names from file as you were doing in your own example. And do the counting while your are reading the file itself.
        while (<FILE>) { ## extract NAME from the record ## count it $names{$name}++; }