Assuming that is strictly 2-dimensional and all strings, that can be
$matrix = { a => {c => 'x', d => 'y'}, b => {c => 'w', d => 'z'}};
foreach my $key1 (keys %$matrix) {
foreach my $key2 (keys %{$matrix->{$key1}}) {
print $matrix->{$key1}{$key2}, " ";
}
print "\n";
}
For the keys, you can put a hash inside the loop and append each key each time one is retrieved. At the end, you simply iterate the hash to get back the keys.