Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Musical key/mode finder.

by IndyZ (Friar)
on Feb 17, 2001 at 11:06 UTC ( #59104=snippet: print w/replies, xml ) Need Help??
Description: I started playing bass a while ago, and now I am getting into the music theory part. Since I got tired of figuring out the keys/modes myself, I wrote some perl to do it.

The scripts takes two command line arguments, the key and then the mode. If the key is not specified, C is assumed, and if the mode is not specified, major is assumed. See the source for valid keys.

Update: I fixed a bug in the notes array (had "G G", instead of "G G#"). Thanks for the msg jeffa.
Update Again: I fixed the bug where invalid keys/modes weren't recognized.
Yet Another Update: Added ionian (instead of just "major").

Things that still need to be fixed:

  • Ouput flats (b). See the first comment below. I have no idea how to do this properly, as saying something like A# or Bb is just "known", there aren't any progmatic rules for it.
  • Recognize flats on the command line. el-moe suggested adding "rocker keys", which have flats (Ab, Bb, Eb, Gb).
      Maybe I'll fix it when I get the time. Our maybe one of you could do it ;-).

$key = uc(shift || "C");
$mode = lc(shift || "major");

@notes = qw(A A# B C C# D D# E F F# G G# A A# B C C# D D# E F F# G G#)
%modes = ("major", -1, "ionian", -1, "dorian", 0, "phrygian", 1, "lydi
+an", 2, 
          "mixolydian", 3, "aeolian", 4, "locrian", 5);
@steps = qw(2 2 1 2 2 2 1);

$notematch = join "|", @notes;
if (($key !~ /($notematch)/) || !(exists $modes{$mode})) {die "Invalid
+ key or mode!\n"}

while ($notes[0] ne $key) {
       push(@notes, shift(@notes));

for (0 .. $modes{"$mode"}) {
       push(@steps, shift(@steps));

unshift(@steps, 0);

foreach $i (@steps) {
       $index += $i;
       print $notes[$index] . " ";
Replies are listed 'Best First'.
Re: Musical key/mode finder.
by Anonymous Monk on Mar 09, 2001 at 23:52 UTC

    Cool idea - glad to see that code can express music as much as it does anything else :)

    Just 2 offtopic suggestions... What you have listed as "major" is really called the "ionian" mode - it *does* happen to be the major scale, but it's got a diff name.

    Also, you might want to consider accomodating flats when you spell out the mode (I don't know right away how you could do that). The reason is that the "a phrygian" mode (just to name one) would normally be notated "A Bb C D..." instead of "A A# C D..."

    Just my 2 cents...

    I still dig this tough - I've been playing around with it all morning :)


Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: snippet [id://59104]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2022-08-18 04:06 GMT
Find Nodes?
    Voting Booth?

    No recent polls found