Solved

creating a hash

Posted on 2000-03-25
1
173 Views
Last Modified: 2010-03-05
I have a file containing IP addresses. I want to read a file, and make a hash with IPs being the keys and the number of times that IP appears in the file as the value. So a file like this:


0.0.0.0
1.2.3.4
0.0.0.0
4.5.6.7
0.0.0.0
1.2.3.4

would create a hash like this:

%ips = (

0.0.0.0 => 1,
1.2.3.4 => 2,
4.5.6.7 => 3,

);

What I really need this for is counting IP accesses in a log file. I'll parse the log file, and:

1. if the IP is not already in the hash, add a key/value pair of <IP>=>"1".

2. if the IP is already in the hash, increment the value.

(how is this done?)

-Mike K.
0
Comment
Question by:lunaboy
1 Comment
 
LVL 19

Accepted Solution

by:
Kim Ryan earned 50 total points
ID: 2657502
open(FH,"<ip_access.txt");
while (<FH>)
{
   chomp($_);
   $current_ip = $_;
   # increment occurence count, stored as value
   $ips{$current_ip}++;
}
close(FH);

foreach $ip (sort keys %ips)
{
   print("$ip was hit $ips{$ip} times\n");
}
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
In the distant past (last year) I hacked together a little toy that would allow a couple of Manager types to query, preview, and extract data from a number of MongoDB instances, to their tool of choice: Excel (http://dilbert.com/strips/comic/2007-08…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

813 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now