in reply to count string occurance

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!

Replies are listed 'Best First'.
Re: Re: count string occurance
by softworkz (Monk) on Jul 27, 2001 at 22:43 UTC
    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}++; }
        Thanks a bunch guys, this is what I decided to go with.
        #!/usr/bin/perl -w use win32; use strict; %hash = (); my $user_usage = $in_file."_user_usage.txt"; open(FILE,"$dups") || die "user_time.pl can't open: $!"; open(USERTIME,">$user_usage") || die "user_time.pl can't open: $!"; # Define the output file format our $UserID="UserID"; our $days="Usage"; format USERTIME= @<<<<<<<<<<<<<@>>>>>>> $UserID, $days . #write the title line write(USERTIME); my $user; my $time; my $date; my $node; while (<FILE>) { chomp; next unless ( ($_ =~ /$in_year/) ); ($user, $node, $date) = split; push(@{$hash{$user." ".$date}}, $node); } foreach $user(sort keys %hash ) { $time = @{$hash{$user}++}; #print $user, " ", $time, "\n"; print USERTIME $user, " ", $time, "\n"; } close FILE; close USERTIME;