in reply to Count occurences of numbers
#!/usr/bin/perl -w use strict; # always good unshift(@INC,"$ENV{'PWD'}"); use List::Util qw(max) ; # I could not find a "Util", but this one +seems fine ;-) my $file_name; my $ans; if (@ARGV == 1) { chomp ($file_name=$ARGV[0]); } else { print "\n\nPlease enter the file name to certify: "; chomp ($file_name=<STDIN>); while(1) { print "\n\nYou entered $file_name - is this correct? <y or n>:"; chomp ($ans=<STDIN>); if ($ans =~ /[Nn]/) { print "\n\nPlease enter the server name: "; chomp ($file_name=<STDIN>); next; } elsif ($ans =~ /[Yy]/) { last; } else { next; } } } open(STUFF,"<$file_name") or die "$!"; my %number_ids = () ; my $no_of_groups = 0; # used to count the number of groups of that +file while (my $line = <STUFF>) { $line =~ s/\s+\z// ; $line =~ s/\A\s+// ; my @csv = split(/:/, $line) ; if (defined($csv[1]) && ($csv[1] =~ m{((CO)\d{5})})) { my $num = $1; # my necessary due to strictures $number_ids{$num}++; $no_of_groups++; # increment Group Counter } elsif (defined($csv[0]) && ($csv[0] =~ m/^Group.*/i)) { show_most_popular(\%number_ids); print "$csv[1],"; %number_ids = (); } else { # what to do we do with peculiar lines? }; }; show_most_popular(\%number_ids); sub show_most_popular { my ($r_ids) = @_ ; return if !%$r_ids ; my $max = max(values %$r_ids) ; my @popular = () ; while (my ($id, $count) = each %$r_ids) { if ($count == $max) { push @popular, $id ; } ; } ; print join(',', sort @popular), " appeared most and $max out of $n +o_of_groups times\n"; # output as requested ;-) } ;
|
|---|