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        


In reply to Re: Don't-Repeat-Myself code for improvement (low) by tye
in thread Don't-Repeat-Myself code for improvement by Cody Pendant

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.