# simple test for (0, 1, 2, 3, 4, 5, 6, 0, 0, 4) { print "$_ ", cache($_), "\n"; } { my @order; my %cache; sub cache { my ($key) = @_; # this number would need tweaking if (@order > 5) { delete $cache{ shift @order }; } unless (exists $cache{$key}) { push @order, $key; $cache{$key} = some_expensive_func($key); } return $cache{$key}; } } # here is where you would build your statement handles sub some_expensive_func { $_[0] + 5 * 3; }