On Tue, 7 Dec 2004, Jeffrey Paul Burger wrote:

> FYI, the ultimate goal of the routine this is part of is to randomly 
> select a file corresponding to specified graphic file types within a 
> directory or subdirectory. Since the directories in question will 
> typically only contain graphic files, I'm not trying to go crazy 
> here... unless somebody has an idea of other common issues.

I have a similar script on my site, but I use it to select a random 
stylesheet instead of a random image. Same idea though. 

  #!/usr/bin/perl -w

  use strict;
  use CGI;

  my $q = new CGI;
  my @sheets = <*.css>;

  use List::Util 'shuffle';
  @sheets    = shuffle( @sheets );

  my $i     = rand @sheets;
  my $sheet = $sheets[$i];

  print $q->redirect( $sheet );

You could get the same effect if you use, say, <*.gif> or <*.jpg>.

 
> Aside from the above problem, I've pretty much got this all working 
> with one other exception: I'm thinking there must be a more efficient 
> way to test for an empty directory than reading the directory into 
> @file_list, removing the files that begin with periods as discussed 
> above, and then testing for an empty array?

Well, you can do some of your testing while populating @file_list:

  opendir(DIR, $dirname) or die "can't opendir $dirname: $!";
  while (defined($file = readdir(DIR))) {
      next if $file =~ /^\./;
      push @file_list, $file;
  }
  closedir(DIR);

Or even something like this ought to work:

  @file_list = grep { /^\./i } readdir(DIR);

If you have a copy of the _Perl Cookbook_, section 9.6 discusses some of 
these issues in more detail...
 

-- 
Chris Devers

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to