in reply to random file selection

You could List::Util::shuffle or fisher-yates the directory and then take a slice of the resulting array.

!/usr/bin/perl -wd use IO::Dir; tie %dir, IO::Dir, "."; @files = grep { -f } keys %dir; fisher_yates_shuffle( \@files ); print $files[$_],"\n" for 0 .. 5; # right from the faq sub fisher_yates_shuffle { my $deck = shift; # $deck is a reference to an array my $i = @$deck; while ($i--) { my $j = int rand ($i+1); @$deck[$i,$j] = @$deck[$j,$i]; } }

or

!/usr/bin/perl -wd use IO::Dir; use List::Util 'shuffle'; tie %dir, IO::Dir, "."; @files = grep { -f } keys %dir; @shuff = shuffle(@files); print $shuff[$_],"\n" for 0 .. 5;

-derby

Replies are listed 'Best First'.
Re: Re: random file selection
by Anonymous Monk on Jun 13, 2003 at 07:42 UTC
    The code at the bottom of this post seems to work nicely. Except that it only works with .pl files in the directory. Why?
      because the others are directories? The -f portion of the snippet extracts only the plaintext files from the list (see perlfunc:_X). Without a listing from the target directory, I cannot be more specific.

      -derby