Link to home
Start Free TrialLog in
Avatar of Skeeter87
Skeeter87

asked on

1 random dbm record

Im using these lines to retrieve records from my database.. It works
fine but I want to display only 1 RANDOM record at a time, which
ofcourse meets all criteria. To be honoust I dont have a clue  how to
display 1 random record at a time..but I'm sure you can help me !?


#!/usr/bin/perl
use CGI;
$q=new CGI;
print "Content-Type: text/html\n\n";

$name = "goods";
die "Missing DBM name.\n" unless $name;
dbmopen(%map,$name,0666);
$rec = 0;
while (($key,$val)=each(%map)) {

($item1,$item2,$item3,$item4) = split("\t",$val);
if ($item2 eq "Radio") {

## check $item3 for "philips"
print qq{$item2<br>};
}}
dbmclose(%map);
exit;
ASKER CERTIFIED SOLUTION
Avatar of ahoffmann
ahoffmann
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Skeeter87
Skeeter87

ASKER

Thanks for replying, I've tested it but it doesnt print any record (there are six records in the database)
When I add print @vals; beneath the 'while' line, it prints out the records...
However the split doesnt seem too function ..

Can this method also be used when used with a couple of thousands of records ?
> doesnt print any record
hmm, can't test you example, just the method
probaly this is a better attempt:

 while (($key,$val)=each(%map)) { push @vals, rand($.) . "\t" . $val; }
@vals=sort @vals;
($dumm,$item1,$item2,$item3,$item4) = split("\t",$vals[0]);

if this fails too, please check if your $item2 contains an expected value


> Can this method also be used when used with a couple of thousands of records ?
it can, but it will be a waste of resources if you just need one of them
I'd use a numeric index in the dbm file and use rand() to select one index randomly, that avoids reading the complete file into memory.
I got it too work !! thanks....

Can you give me an example on how to implentate such an numeric index ?
as you do not use the key in your example, I'd use that as simple integer
then you have to cast the result of rand() to an integer, that's it ..
ok, thank you very much