in reply to Pick random file and print

Here's a commonly used trick, adapted from "get a random line from a file":
my ($n, $file); opendir DIR, $path or die "can't opendir $path: $!"; while (defined (my $f = readdir DIR)) { next if -d "$path/$f"; $file = $f if rand(++$n) < 1; } closedir DIR; $file = "$path/$f";

_____________________________________________________
Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a job (NYC-area)
s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Replies are listed 'Best First'.
(wil) Re: Pick random file and print
by wil (Priest) on May 07, 2002 at 14:20 UTC
    Thank you for the replies fellow monks!

    I haven't been able to find much on PM about glob v. readdir but what I did find (I don't use glob, I use readdir) suggests that I should be using readdir, and japhy, your code uses readdir so I assume this is the way forward. I guess the next step is to benchmark.

    Thanks for your help!

    - wil