Perl bounded LRU cache with hash and list
Perl
use strict;
use warnings;
sub lru_cache {
my ($max) = @_;
my (%map, @order);
my $touch = sub { my $k = shift; @order = (grep { $_ ne $k } @order, $k) };
return {
get => sub { exists $map{$_[0]} ? do { $touch->($_[0]); $map{$_[0]} } : undef },
set => sub {
$touch->($_[0]);
$map{$_[0]} = $_[1];
delete $map{ shift @order } while @order > $max;
$_[1];
},
};
}
my $c = lru_cache(2);
$c->{set}->(a => 1); $c->{set}->(b => 2); $c->{set}->(c => 3);
print $c->{get}->('a') // 'miss', "\n";