[EMAIL PROTECTED] wrote:
I know how to and can successfully open a directory , but i need to choose
a file within the directory at random to verify the data on. does anyone
have any suggestions of how to do this? i'm thinking it could take a while
to create an array of the file names and then randomly pick a slot there,
but that;s all i can think of right now.
There is one way to do it, if you already know that there are exactly n
directory entries to choose from.
Read the 1st directory entry; if rand(n) < 1, use it.
Read the 2nd; if rand(n-1) < 1, use it.
Read the 3rd; if rand(n-2) < 1, use it
...
Read the last; if rand(n-(n-1)) < 1, use it.
(rand(n-(n-1)) simplifies to rand(1), which is always < 1)
Unfortunately, this is not likely to do you any good, because you need
to know the value of n before starting, and the correct value can be
obtained only by reading the directory in the first place. So....
my @entries;
opendir MYDIR, $directory;
while (my $entry = readdir MYDIR) {
next if -d "$directory/$entry";
push @entries, $entry;
}
closedir MYDIR;
my $chosenfile = @entries[int rand ($#entries + 1)];
--
John W. Kennedy
"Information is light. Information, in itself, about anything, is light."
-- Tom Stoppard. "Night and Day"
_______________________________________________
ActivePerl mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs