Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 304
  • Last Modified:

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;
0
Skeeter87
Asked:
Skeeter87
  • 4
  • 3
1 Solution
 
ahoffmannCommented:
while (($key,$val)=each(%map)) { push @vals, $val . "\t" . rand($.); }
@vals=sort @vals;
($item1,$item2,$item3,$item4,$dumm) = split("\t",$vals[0]);
if ($item2 eq "Radio") { print qq{$item2<br>};
0
 
Skeeter87Author Commented:
Thanks for replying, I've tested it but it doesnt print any record (there are six records in the database)
0
 
Skeeter87Author Commented:
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 ?
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
ahoffmannCommented:
> 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.
0
 
Skeeter87Author Commented:
I got it too work !! thanks....

Can you give me an example on how to implentate such an numeric index ?
0
 
ahoffmannCommented:
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 ..
0
 
Skeeter87Author Commented:
ok, thank you very much
0

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now