On Fri, 29 Jul 2005 12:05:09 -0700, you 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.

If you want a truly random selection, you obviously need to read the
entire directory, but you don't have to save every entry. I would do
something like this:

my $file_count = 0;  # count of eligible files
my $random_file;  # name of chosen file

opendir DIRHANDLE, $dirname or die "OOPS! $!";
while (my $filename = readdir(DIRHANDLE))  {
    # Assuming subdirectories are ignored. Other criteria
    # can be added here.
    next if -d "$dirname/$filename";
    $random_file = "$dirname/$filename" if rand < 1/(++$file_count);
}


-- 
Eric Amick
Columbia, MD

_______________________________________________
ActivePerl mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to