Run a series of code only once within void loop

I am making a custom bookshelf and have already gotten a light to turn on only when the door is opened using a Reed Switch(door sensor), but I'm finding that playing a short tune is more difficult(I've only been using arduino for like 4 days). I can get my little tone and delay melody to play just fine over the speaker I have hooked up, but cannot get it to stop playing after it goes through the tune once(about 2.5 seconds). Is there a way to make certain lines of code only run through once within a void loop and then wait to be triggered again?

Use a boolean variable as a flag for whether or not it's already been done.

boolean itAlreadyHappened = false;

void loop(){

                      itAlreadyHappened = true;
              itAlreadyHappened = false;