Category: | Miscellaneous |
Author/Contact Info | mr.nick |
Description: | A very simple, small, efficient (n) cache that maintains a limited set of items. Accessing an items moves it to the front of the cache which speeds location and refreshes it's age in the cache. |
package cache;
use strict;
######################################################################
+########
sub new {
my $class=shift;
my $size=shift;
my $self=bless {};
$size=30 unless $size;
$self->{array}=[];
$self->{size}=$size;
$self;
}
sub ins {
my $self=shift;
my $id=shift;
my $data=shift;
my $array=$self->{array};
unshift @$array,[$id,$data];
if ($#{$array} > $self->{size}) {
pop @$array;
}
}
sub get {
my $self=shift;
my $id=shift;
my $array=$self->{array};
my $data;
for my $p (0..$#{$array}) {
if ($array->[$p]->[0] eq $id) {
$data=$array->[$p]->[1];
splice(@$array,$p,1);
unshift @$array,[$id,$data];
last;
}
}
return unless defined $data;
$data;
}
sub del {
my $self=shift;
my $id=shift;
my $array=$self->{array};
my $data;
for my $p (0..$#{$array}) {
if ($array->[$p]->[0] eq $id) {
splice(@$array,$p,1);
last;
}
}
}
sub show {
my $self=shift;
my $array=$self->{array};
local $_;
for (@$array) {
print "id $_->[0] data $_->[1]\n";
}
}
1;
|
Back to
Code Catacombs