in reply to Counting the Number of Times and IP Appears

Rule #1: Please state how it's not working.

Rule #2: Please show us sample input data.

Lot's of little problems, but let's focus on the important stuff first.

my($src, $dst, $rule1) = (split /,/)[1];
(split /,/)[1] returns the element with index 1 (2nd element) in the list that split returns. If you really want $src to be the 1st element (index 0), use (split /,/)[0]. (See split for other options.)

Since you don't need the other vars, that reduces to

my $src = (split /,/)[0];
---
$hash{$src} = $src;
The hash value can contain anything, it doesn't need to be the hash key. I would rewrite this as
$hash{$src}++; # count occurrences
---
next if $src =~ /$hash{$src}/;
This is useless, as it's the last statement in the loop, and $hash{$src} has just been set to $src on the line before.

There's no reason to step through the file twice, as you already have all of the info stored. Instead of all the rest, do this

foreach (keys %hash) { print "$_ was seen $hash{$_} times\n"; }
Cheers,

-QM
--
Quantum Mechanics: The dreams stuff is made of

Replies are listed 'Best First'.
Re: Re: Counting the Number of Times and IP Appears
by Dru (Hermit) on Feb 20, 2004 at 03:41 UTC
    Thank you everyone for your help, here's what my final code looks like that does what I need.
    # Script to go through file and count the number of # times an ip appears; use strict; use warnings; my $file = 'd:\temp\text.csv'; my %hash; open (FILE, $file) or die "Can't open $file: $!\n"; while (<FILE>){ my($src) = (split /,/)[1]; $hash{$src}++; } foreach my $ip (sort({$hash{$b} <=> $hash{$a}} keys %hash)) { print "$ip appears $hash{$ip} times\n"; }