Yes. That is, instead of all the code in the OP, you would want something like this:
#!/usr/bin/perl
use strict;
my %idcount;
while (<>) {
if ( /,CO(\d+)\s/ ) {
$idcount{$1}++
}
}
my ( $highest ) = sort { $idcount{$b} <=> $idcount{$a} } keys %idcount
+;
my $total = 0;
$total += $_ for ( values %idcount );
print "Highest count was for group CO$highest, with $idcount{$highest}
+ out of $total users\n";
For the sample data in the OP, that prints:
Highest count was for group CO12345, with 4 out of 6 users
(which I got by running the script in a terminal window, then pasting the 6 lines of data into the window, to emulate "typing" on stdin; the same result would happen by piping those six lines to the perl script from some other process, or storing them in a file and giving the file name as the sole command-line arg when running the script).
UPDATED to include declaring, computing and printing "$total" (as per the OP spec).
Oops... another update -- forgot about the case of possible ties for "highest". So, in place of the one line above that declares/assigns a value to $highest, you would need these two lines, which will set $highest to be a string of one or more comma-separated group-ids (including "CO" before the digits of non-initial id values):
my ($maxcount) = sort { $idcount{$b} <=> $idcount{$a} } keys %idcount;
my $highest = join(",CO", grep { $idcount{$_} == $maxcount } keys %idc
+ount );
Nothing else needs to change. Then replace "$idcount{$highest}" with "$maxcount" in the print statement. |