MadSci Net: Computer Science (View this file without Frames)
Search MadSci:

Subject: Re: Random web page displaying

Date: Wed Apr 22 17:05:53 1998
Posted by Ricky J. Sethi
Position: PhD

Hi Nauzad,

If I understand the problem right, you'd like to have a little script that picks a file at random and then does something to it. Here is a little code fragment in Perl. It makes a couple of assumptions but you should get the general idea and be able to customize it for your needs. In particular, it assumes that you're on a Unix system; but, since Perl is readily available on almost all platforms, you should be able to tweak this to work for your particular situation relatively easily. Here's the code:

#!/usr/local/bin/perl -w

# Initialize index variable
$x = 0;

# Loop through all the files in the current directory
# and store their names in an array
foreach $file (`ls`) {
    $someArray[$x] = $file;
    $x++;
}

# Initialize the random function
srand;
# Get the random number (it's -1 because the array
# index starts at 0
$y = int(rand(@someArray) - 1);

# You should replace this line with whatever you'd
# like to do with the file; This line just prints
# out the name of the file.
print "The file is $someArray[$y]\n";

Well, I hope that does what you wanted it to do. Of course, we could make the program a lot more sophisticated (it could check for directories, for starters) and make it do more than just print the name of the file. But, it should work as a nice starting point for most purposes. If it doesn't, please feel free to write back to me.

Regards,

Rick.


For more information on Computer Science, try the Computer Science links in the MadSci Library

MadSci Home | Information | Search | MAD Library | MAD Labs | MAD FAQs | Ask a ? | Join Us!
Help Support MadSci


www@madsci.org
© 1995-2024 MadSci℠ Network. All rights reserved.