for(1..5){ # should be an infinite loop $pid=fork(); if($pid==0){ my $m=getmusic(); if($m){exec 'afplay "'.$m.'"' or die} else{exec 'sleep 1'} } while (wait() != -1){ my $m=getmusic(); unless($m){ # somehow stop the music currently playing }else{ sleep 1; } } } sub getmusic{ open MFILE, "$path/music.txt" or die; my $m=; chomp $m; close MFILE; return $m; }