You have to make sure, though, that your @p and @m Arrays are expanded to the appropriate number of elements, corresponding to the number of letters from the alphabet that you use. So if you eg. use the letters from A to D then @p and @m should both have 4 elements.
Code written by Hofmator and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.