💾 Archived View for thrig.me › blog › 2023 › 08 › 08 › least-recently-used.pl captured on 2024-05-10 at 12:22:13.

View Raw

More Information

⬅️ Previous capture (2023-09-08)

-=-=-=-=-=-=-

#!/usr/bin/perl
use 5.36.0;
use List::Util 'shuffle';

# given an array reference, picks one item randomly from the front,
# and returns that item after moving said item to the end
sub picker ( $ref, $shuffle = 1, $bounds = ~0 ) {
    if    ( !$bounds or $bounds > $#$ref ) { $bounds = $#$ref }
    elsif ( $bounds < 1 )                  { $bounds = 1 }
    my @intervals = $shuffle ? shuffle @$ref : @$ref;
    my $last      = $#intervals;

    sub () {
        my $pick = rand $bounds;
        @intervals[ $pick, $last ] = @intervals[ $last, $pick ];
        return $intervals[$last];
    }
}

my $fn = picker [ 1, 2, 3 ];
say $fn->() for 1 .. 10;