You need to cope with scoping. There are variables $key and $value defined on lines 3 and 6 (outside the loop), and then you define another pair of them inside the loop (lines 12 and 15). Because you use my again, they are not reused, but created anew, masking earlier declaration. Had you used warnings and strict (which is recommended for all programs; use diagnostics will also help you), you would have received a message: "my" variable $key masks earlier declaration in same scope at ..., which means:
A "my", "our" or "state" variable has been redeclared in
the current scope or statement, effectively eliminating all access
to the previous instance. This is almost always a typographical
error. Note that the earlier variable will still exist until the
end of the scope or until all closure referents to it are
destroyed.
(taken from
perldiag). Because of this your while loop checks for upper-scope variables, which get assigned in the beginning of the program, but modifies other ones, which were created inside the loop.
Solution (simplified): use my only once per variable.