[EMAIL PROTECTED] wrote:
"John W. Kennedy" <[EMAIL PROTECTED]> 08/01/2005 04:46 PM

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






[EMAIL PROTECTED] wrote:

"John W. Kennedy" <[EMAIL PROTECTED]> [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-
that makes sense now. for some reason i was thinking it was 0<= rand <= n shifted to 1 <= rand <= n. while i have fixed that, i am still getting a concatination error. I dont quite understand why it is not pulling the file. it gives me this when i try choosing the file the line before as well.

I think you'll have to give your exact code and the exact error message.

--
John W. Kennedy
"You can, if you wish, class all science-fiction together; but it is about as perceptive as classing the works of Ballantyne, Conrad and W. W. Jacobs together as the 'sea-story' and then criticizing _that_."
  -- C. S. Lewis.  "An Experiment in Criticism"

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

Reply via email to