Cap'n Steve has asked for the wisdom of the Perl Monks concerning the following question:
What I want this script to do is go through the specified directory with File::Find and build a list of all sound files. It then uses File::Stat to give each one a score; newer files get a point, files that haven't been accessed in a while get a point, etc. I want it to play a random music file, but the files with higher scores should get played more often.
Problem 1 comes from the fact that one of the modules apparently touches all the files, since last access times are the same throughout the directory. Problem 2 is adding the bias. Not only is it massively ugly (please don't kick me off the site for using all those eval()s), but it also doesn't seem to work.
#!/usr/bin/perl use warnings; use diagnostics; use File::Find; use File::stat; my (%files, %score, $rand, $array, @file0, @file1, @file2, @file3, @fi +le4, @file5, @file6, @file7, @file8); my $epoch = time(); find(\&file_check, qw(C:/music)); while (my($filename, $stats) = each %files) { # accessed in the last 2 days #if ($stats->atime + 60 * 60 * 24 * 2 >= $epoch) { # delete $score{$filename}; # next; #} # not accessed in the last month if ($stats->atime + 60 * 60 * 24 * 30 < $epoch) { $score{$filename} += 4; } # created in the last week if ($stats->mtime + 60 * 60 * 24 * 7 >= $epoch) { $score{$filename} += 2; } } while (my($file, $score) = each %score) { $file =~ s/'/\\'/g; eval("push \@file$score, '$file';"); } &pick_another(); sub file_check() { if (/\.(mp3|wav|wma)$/i) { $files{$File::Find::name} = stat($File::Find::name); $score{$File::Find::name} = 0; } } sub continue_loop() { print "\n\nPlay another (y/n)?"; my $response = <STDIN>; chomp($response); if (lc($response) eq 'n') { exit 0; } else { pick_another(); } } my $length; sub add_bias() { $array = int(rand() * 9); if (int(rand() * 10) % 2) { $array -= 2; } elsif (int(rand() * 10) % 5) { $array--; } eval("\$length = \@file$array;"); $rand = int(rand($length - 1)); my $value = '$file' . $array . '[' . $rand . ']'; if ($rand > $length || $rand < 0 || $array > 8 || $length == 0 + || eval($value) eq '') { return 0; } else { return 1; } } sub pick_another() { while (!add_bias()) { next; } my $variable = '$file' . $array . '[' . $rand . ']'; my $command = "\\\"c:\Program Files\Windows Media Player\wmpla +yer.exe\\\" \\\"$variable\\\""; print "Playing file with score $array\n"; eval("`$command`;"); eval("delete $variable;"); continue_loop(); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Opening random files (with bias) based on File::Stat information.
by blokhead (Monsignor) on Mar 19, 2006 at 02:46 UTC | |
|
Re: Opening random files (with bias) based on File::Stat information.
by xdg (Monsignor) on Mar 19, 2006 at 14:05 UTC | |
|
Re: Opening random files (with bias) based on File::Stat information.
by Cap'n Steve (Friar) on Mar 20, 2006 at 03:41 UTC |