Cache-Sliding

 view release on metacpan or  search on metacpan

lib/Cache/Sliding.pm  view on Meta::CPAN

package Cache::Sliding;
use 5.010001;
use warnings;
use strict;
use utf8;
use Carp;

our $VERSION = 'v2.0.1';

use Scalar::Util qw( weaken );
use EV;


sub new {
    my ($class, $expire_after) = @_;
    my $self = {
        L1      => {},
        L2      => {},
        t       => undef,
    };
    weaken(my $this = $self);
    $self->{t} = EV::timer $expire_after, $expire_after, sub { if ($this) {
        $this->{L2} = $this->{L1};
        $this->{L1} = {};
    } };
    return bless $self, $class;
}

sub get {
    my ($self, $key) = @_;
    if (exists $self->{L1}{$key}) {
        return $self->{L1}{$key};
    }
    elsif (exists $self->{L2}{$key}) {
        return ($self->{L1}{$key} = delete $self->{L2}{$key});
    }
    return;
}

sub set {   ## no critic (ProhibitAmbiguousNames)
    my ($self, $key, $value) = @_;
    return ($self->{L1}{$key} = $value);
}

sub del {
    my ($self, $key) = @_;
    delete $self->{L2}{$key};
    delete $self->{L1}{$key};
    return;
}


1; # Magic true value required at end of module
__END__

=encoding utf8

=head1 NAME

Cache::Sliding - Cache using sliding time-based expiration strategy


=head1 VERSION

This document describes Cache::Sliding version v2.0.1


=head1 SYNOPSIS

    use Cache::Sliding;

    $cache = Cache::Sliding->new(10*60);

    $cache->set($key, $value);
    $value = $cache->get($key);
    $cache->del($key);


=head1 DESCRIPTION

Implement caching object using sliding time-based expiration strategy



( run in 2.691 seconds using v1.01-cache-2.11-cpan-39bf76dae61 )