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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |