in reply to local and global variable problem

Welcome to the world of Debugging My Code.

At first glance I'd say that %matrix doen't contain what you think it does. Add this following the inner foreach:

print ("DEBUG>>", $matrix->{$key}->{$key2}, "<<DEBUG\n");
to see what is really in your matrix. Then, start working through your logic and figure out why those fields are empty.

I Go Back to Sleep, Now.