I have the following problem.

Cron job runs repeatedly, picks a random item from a list and does something with it.

Now I want to make sure that I don't repeat the items. If I chose "foo" recently, I shouldn't use it again.

So I came up with this code, saving the three most recent items used in a DBM hash which I sort by time, but it seems like I'm doing far too much work and probably not thinking Perlishly (I've been spending too much time with other languages!).

Any suggestions for improvement?

use strict; use warnings; my @ids = qw(a b c d e f g h); my $chosen_id = ''; dbmopen( my %recent_ids, 'recent', 0777 ) || die "$!"; while (1) { $chosen_id = @ids[ int( rand(@ids) ) ]; print "chosen: $chosen_id\n"; if ( !defined( $recent_ids{$chosen_id} ) ) { last } else { print "problem: $chosen_id is on the recent list, choose ag +ain\n" } } $recent_ids{$chosen_id} = time(); my $count = 0; foreach ( sort { $recent_ids{$b} <=> $recent_ids{$a} } ( keys(%recent_ +ids) ) ) { $count++; if ( $count > 3 ) { print "$_ is the oldest id, remove it\n"; delete( $recent_ids{$_} ); } } print "hash is now:\n"; while ( my ( $key, $value ) = each(%recent_ids) ) { print "$key - $value\n"; } dbmclose(%recent_ids);


($_='kkvvttuu bbooppuuiiffss qqffssmm iibbddllffss')
=~y~b-v~a-z~s; print

In reply to 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.