Here is a little more than you need. The pattern match grabs everything up to the first space. The keys in the hash contain the unique ip addresses. The values tell you how many times they appeared during processing. This is a classic counting example.
use strict;
use warnings;
use Socket;
my @ip = ( '159.230.1.1 255.255.224.0',
'159.230.1.20 255.255.252.0',
'158.230.1.3 255.255.255.0',
'159.230.1.3 255.255.255.0',
'159.230.1.20 255.255.1.1' );
print join ("\n", @ip);
print "\n\n";
my %count;
foreach (@ip) {
$count{inet_aton($&)}++ if /159\.230\..*?( |$)/;
}
open(FILE, '>ip.txt');
foreach (sort keys %count) {
print inet_ntoa($_)." appears $count{$_} times.\n";
print FILE inet_ntoa($_)."\n";
}
close FILE
UPDATE: Good point on the sort not working out. I put the inet functions in like other posts did. I reread the question and realized the user only wants 159.230 address so I changed the pattern match from /.*? /. That change will also get rid of the leading text if it exists. Of course the \d{1,3} match the other poster mentioned does a little more verification on your data if you decide you need it.
Good luck.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.