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

I think I'm close at finding how many times an element appears in the log file from each array, but I am getting the same results for each element. Here is my output when the script is ran:
192.168.17.10 was seen 148 times http was seen 148 times 192.168.12.187 was seen 148 times ftp was seen 148 times

What am I doing wrong? Here is the code:
#!/usr/bin/perl -w use strict; my $log = './logfile'; my (@data, @service, @dst, %count, %counts, %hash, %sizes, $dst, $serv +ice, $ip, $times); &check("192.168.47.3"); sub check { $ip = $_[0]; open (LOG, $log) or die "Can't open $log: $!"; while (<LOG>){ push (@data, $_) if $_ =~ /$ip/; foreach (@data){ ($dst, $service) = (split /;/)[11,12]; next if m/^\s*$/; #skip any empty lines push(@service, $service); push(@dst, $dst); } } @service = &duplicates(@service); @dst = &duplicates(@dst); foreach (@data){ foreach my $i (@dst){ $count{$i}++; } foreach my $j (@service){ $count{$j}++; } } } while (my ($key, $count) = each(%count)){ print "$key was seen $count times\n"; } sub duplicates { my @array = @_; my %saw; @array = grep(!$saw{$_}++, @array); }

Thanks,
Dru
Another satisfied monk.

Replies are listed 'Best First'.
(Ovid) Re: Number of times each element in an array appears.
by Ovid (Cardinal) on Jan 01, 2002 at 01:19 UTC

    Your problem is in this loop:

    foreach (@data){ foreach my $i (@dst){ $count{$i}++; } foreach my $j (@service){ $count{$j}++; } }

    Since you apparently have 148 lines of @data, you're simply counting that for each destination and service. Count them when they come in:

    #!/usr/bin/perl -w use strict; my $log = './logfile'; my (@data, %count); my $count = &check("192.168.47.3"); sub check { my $ip = $_[0]; my %count; # open LOG, "< $log" or die "Can't open $log: $!"; while (<DATA>){ push (@data, $_) if $_ =~ /$ip/; } # close LOG; foreach (@data){ my ($dst, $service) = (split /;/)[11,12]; $count{ $service }++; $count{ $dst }++; } return \%count; } while (my ($key, $count) = each(%$count)){ print "$key was seen $count times\n"; } __DATA__ 0;1;2;3;4;5;6;7;8;9;10;onedest;http;192.168.47.3 0;1;2;3;4;5;6;7;8;9;10;twodest;http;192.168.47.3 0;1;2;3;4;5;6;7;8;9;10;onedest;http;192.168.47.3 0;1;2;3;4;5;6;7;8;9;10;onedest;http;192.168.47.3 0;1;2;3;4;5;6;7;8;9;10;onedest;ftp;192.168.47.3

    Output:

    twodest was seen 1 times http was seen 4 times ftp was seen 1 times onedest was seen 4 times

    Cheers,
    Ovid

    Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.