[EMAIL PROTECTED] wrote:
"John W. Kennedy" <[EMAIL PROTECTED]> 07/29/2005 04:13 PM

To
[EMAIL PROTECTED]
cc
[email protected]
Subject
Re: randomly choosing a file






[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.




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)];


this looks like a more efficient variation upon what i was thinking. i have one question though.. the array starts at 0 for an index, doesn't $#var give one less than the element in the array since it uses the last index in the array? wouldn't this mean one wants to *1 to make an integer instead of +1 and make the result 1 to [one-greater-than-array] ?

If there are ten directory entries, then $#entries will be 9, and $#entries+1 will be 10. rand(10) yields 0 <= rand < 10. That truncates to 0 <= rand <= 9.

--
John W. Kennedy
"...if you had to fall in love with someone who was evil, I can see why it was her."
  -- "Alias"

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

Reply via email to