in reply to Don't-Repeat-Myself code for improvement
Now that you've replied and shown that most of us were solving the wrong problem...
You can avoid having to use Perl's sort if you use a DBM flavor that allows you some control over how things are indexed. The Berkeley flavor allows that. But I leave the details of that for someone more familiar with Berkeley DBM (or willing to RTFM) since I don't recall the specifics.
Since I don't think DBM offers concurrent write access, I'd probably just go "old school" and implement a simple circular buffer in a file and flock it, but I doubt you'd find this an improvement. (:
use Fcntl ':flock'; sub wasRecentlyUsed { my( $file, $id, $idlen, $count )= @_; $id= pack "a$idlen", $id; flock( $file, LOCK_EX() ) or die "Can't flock: $!"; seek( $file, 0, 0 ) or die "Can't seek: $!"; my $nextPos= _nextPos( $file, $id, $count ); if( $nextPos ) { seek( $file, 0, 0 ) or die "Can't seek: $!"; print $file pack "S", $nextPos or die "Can't print: $!"; } flock( $file, LOCK_UN() ) or die "Can't unflock: $!"; return ! $nextPos; } sub _nextPos { my( $file, $id, $count )= @_; local( $/ )= \4; my $head= <$file>; if( ! $head ) { seek( $file, 0, 0 ) or die "Can't seek: $!"; $head= pack "SS", 0, $count; print $file $head, $id or die "Can't print: $!"; return tell $file; } my $first= tell $file; ( my $next, $count )= unpack "SS", $head; $/= \ length $id; while( <$file> ) { return 0 if $id eq $_; $count--; } seek( $file, $next, 0 ) or die "Can't seek: $!"; print $file $id or die "Can't print: $!"; return $count < 1 ? $first : tell $file; }
- tye
|
|---|