There are many cases where you use a variable that's not defined, out of scope, or not what you think ($key is not a hashref). Luckily you can find all those mistakes by applying three simple rules:
- Add use strict; and use warnings; at the top of your file. Perl will now tell you about those mistakes.
- Declare your variable with my. This way perl can tell when you've made a typo in a variable's name.
- Avoid single letter names, especially $a, which has a special value (some built-ins may use and change it (like sort), and perl won't warn you if you forgot to declare it). $x and $y may be an exception because they are pretty explicit, but only when they are used as coordinates.