Friday, February 13, 2009

25 random songs

Bo hit me with the 25 random songs meme. Who wants to push buttons when you can write a program?
#! /usr/bin/perl

use warnings;
use strict;

use File::Find;

use constant CHOOSE_N => 25;

@ARGV = "." unless @ARGV;

my @mp3;
my $matches = sub {
  push @mp3 => $File::Find::name
    if /\.mp3$/i;
};

find $matches => @ARGV;

# Fisher-Yates-Knuth
for (my $n = $#mp3; $n >= 1; $n--) {
  my $k = int rand($n+1);
  @mp3[$k,$n] = @mp3[$n,$k];
}

for (1 .. CHOOSE_N) {
  last unless @mp3;
  my $song = shift @mp3;

  # e.g., .../Music/Bob Marley/Kaya/08 - Crisis.mp3
  if ($song =~ m!^.*/([^/]+)/[^/]+/\d+\s+-\s+(.+)\.!) {
    my($artist,$title) = ($1,$2);
    print qq{$_. "$title," $artist\n};
  }
}

The output:
  1. "The End," The Doors
  2. "Misty Morning," Bob Marley
  3. "My Mood Swings," Elvis Costello
  4. "Concerto Emperor: II. Adagio un poco moto," Ludwig van Beethoven
  5. "What's the Matter Here?," 10,000 Maniacs
  6. "Trench Town Rock," Bob Marley
  7. "Final Hour," Lauryn Hill
  8. "These Are Days," 10,000 Maniacs
  9. "Want-Ad Blues," John Lee Hooker
  10. "Loser," Beck
  11. "Sonata Pathétique: II. Adagio cantabile" Ludwig van Beethoven
  12. "Peer Gynt Suite No. 2: Ingrid's Lament," Edvard Grieg
  13. "4 Better or 4 Worse (interlude)," The Pharcyde
  14. "Bonita Applebum," A Tribe Called Quest
  15. "Hard Hearted Woman," John Lee Hooker
  16. "Jeremy," Pearl Jam
  17. "Toccata and Fugue in D minor," Johann Sebastian Bach
  18. "Ya Mama," The Pharcyde
  19. "Pennyroyal Tea," Nirvana
  20. "Concerto in C minor for Violin and Oboe," Johann Sebastian Bach
  21. "Sex Type Thing," Stone Temple Pilots
  22. "Drive," R.E.M.
  23. "People Are Strange," The Doors
  24. "Vivrant Thing - Violator (feat. Q-Tip)," A Tribe Called Quest
  25. "The New Pollution," Beck

No comments: