Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

(Ovid) Re: Number of times each element in an array appears.

by Ovid (Cardinal)
on Jan 01, 2002 at 01:19 UTC ( [id://135435]=note: print w/replies, xml ) Need Help??


in reply to Number of times each element in an array appears.

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://135435]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (3)
As of 2024-04-25 23:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found