[Pdx-pm] hashes
Joshua Keroes
jkeroes at eli.net
Tue Jul 29 14:04:32 CDT 2003
On (Tue, Jul 29 10:57), Robby Russell wrote:
> I assume I can ask programming questions here, correct? :-p Since I've
> joined I haven't seen many...anyhoo.
>
> I have a hash...and I'm constantly populuting the hash of ip addresses and
> timestamps.
>
> So, I have a limit of how many timestamps for each ip address in my hash.
>
> %hash_ips
> 1 => 0101010 (timestamp)
> 2 -> 014509249 (timestamp) and so on
>
> It's working all fine and dandy, but I'm not getting rid of hash
> keys/values that are older than a determined # of seconds.
>
> So what I'd like to do is compare each first entry in the hash to the
> current timestamp each time a function is run.
>
> Is there an easy-ish method to accomplishing this?
>
> # Populate hash
> push(@{ $hash_ips{$host} }, $logTime );
>
> The logtimes/current time are in EPOCH as well.
>
> Thanks for any input, (goes back to his cookbooks)
I'm not sure which is more important to you:
1. That the IPs are readily accessible.
2. That the IPs are easily expirable.
In the first case your data-structure looks good. If it's the second
case, then I'd suggest using a heap instead. Heaps have the handy
ability to remain sorted, by say, timestamp.
Here's a quick mockup of a heap implementation using Heap::Simple,
found on CPAN. There are other heap modules out there, this just
happens to be the one I have on my system.
#!/opt/perl580/bin/perl -w
#
# ip_ts_heap.pl - Store IPs in a heap indexed by timestamp
# jkeroes at eli.net 29 Jul 2003
use strict;
use Heap::Simple;
use Data::Dumper;
my $heap = Heap::Simple->new(order => '<',
elements => [ Hash => 'ts' ],
) or die "Can't create new heap";
while ( <DATA> ) {
my ($ts, $ip) = split;
$heap->insert( { ts => $ts, ip => $ip } );
}
print "The heap, internally sorted:\n", Dumper $heap;
print "Deleting all IPs above 1060000003... ";
$heap->extract_upto( 1060000003 );
print "done.\n";
print "The heap, after expiration:\n", Dumper $heap;
exit;
__DATA__
1060000003 10.2.0.0
1060000002 10.9.0.0
1060000005 10.3.0.0
1060000001 10.5.0.0
1060000004 10.1.0.0
1060000006 10.8.0.0
More information about the Pdx-pm-list
mailing list