|
In a message dated 7/29/2005 9:07:50 P.M. Eastern Standard Time,
[EMAIL PROTECTED] writes:
> 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); > } > wouldn't it be simpler to write something like:
my $dirname = "something";
opendir DH, $dirname or die "opening directory $dirname: $!";
my @files = readdir DH;
my $random_file; do {
$random_file = "$dirname/$files[ int rand
@files ]";
} until (-f $random_file and
whatever_other_conditions($random_file));
bill walters
|
_______________________________________________ ActivePerl mailing list [email protected] To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs
