The answer to the second is easy - use a DBM. The best DBM for this kind of task would be DBM::Deep because it allows you to have a Perl datastructure be backed by disk instead of RAM. All the standard Perl datastructure manipulators for hashes and arrays exist and are used just like normal.
The answer to the first is to maintain a list of unchosen items. Once an item is chosen, then you remove it from the list of choosable items and move on. Assuming that there aren't any duplicates, this is best implemented as a set which is usually implemented as a hash in Perl. So, something like:
my %set = ( # Populate this somehow. ); my @keys = keys %set; my $chosen_key = $keys[ rand @keys ]; my $chosen_value = delete $set{ $chosen_key };
Now, if your list of chosen items isn't discrete, then maintain a list of previously chosen items and disregard a choice until it doesn't exist. This is also implemented with a hash, but instead of calling it %set, one generally calls it %seen. Implementation left as an exercise for the reader.
Now, the hard part - doing the DBM bit. Let's say we have a discrete set as per the prior example. Go ahead and seed the DBM file as so:
Now, let's modify our prior example. With a DBM, it looks like:my %set; tie %set, 'DBM::Deep' => { file => 'my_file.db' }; %set = ( # Populate as desired, nesting arrays and hashes as appropriate. );
Alternately, you can choose to use the OO interface which would look like:my %set; tie %set, 'DBM::Deep' => { file => 'my_file.db' }; my @keys = keys %set; my $chosen_key = $keys[ rand @keys ]; my $chosen_value = delete $set{ $chosen_key };
Note the difference between hash notation and hashref notation.my $set = DBM::Deep->new({ file => 'my_file.db', }); my @keys = keys %{ $set }; my $chosen_key = $keys[ rand @keys ]; my $chosen_value = delete $set->{ $chosen_key };
Oh - and if you need them, DBM::Deep also supports transactions and synchronous access.
In reply to Re: Don't-Repeat-Myself code for improvement
by dragonchild
in thread Don't-Repeat-Myself code for improvement
by Cody Pendant
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |