Algorithm-SlidingWindow
view release on metacpan or search on metacpan
A **fixed-capacity sliding window** (overwrite-oldest) implemented with an **array-backed circular buffer**.
When the window is full and you add new items, the **oldest** items are automatically evicted. This is designed for streaming, metrics, logging, and sliding-window workloads where you want to keep only the most recent *N* values.
## Features
- O(1) insertion (`add`) per element
- O(1) random access (`get`)
- O(n) snapshot (`values`)
- Handles **any Perl scalar**: numbers, strings, refs, objects
- Evicted / cleared slots are set to `undef` so references are released promptly
- Minimal method call overhead and predictable behavior
## Install
### From CPAN
```sh
cpanm Algorithm::SlidingWindow
```
### From source (this repository)
#### `oldest() -> $item | undef`
Returns the oldest element without removing it.
#### `newest() -> $item | undef`
Returns the newest element without removing it.
## Behavior notes
- Eviction policy is deterministic: **overwrite-oldest**
- Order is preserved at all times
- Slots are cleared on eviction and `clear()` to help free references promptly
- This module does **not** attempt to emulate Perl array semantics
## Development
### Run tests
```sh
prove -l
```
or CPAN-style:
use strict;
use warnings;
use Test::More;
use Scalar::Util qw(weaken);
use lib 'lib';
use Algorithm::SlidingWindow;
# This test ensures references are released promptly when evicted or cleared.
{
my $w = Algorithm::SlidingWindow->new(capacity => 2);
my $obj1 = bless({}, 'T::Obj');
my $weak1 = $obj1;
weaken($weak1);
my $obj2 = bless({}, 'T::Obj');
my $weak2 = $obj2;
( run in 1.239 second using v1.01-cache-2.11-cpan-0b5f733616e )