PERL: How do i print an associative matrix?

Hello guys,

I have in PERL an associative 2-dimensional array, called matrix. The array (actually the matrix) is made up like this

matrix[a][c] = x;
matrix[a][d] = y;
matrix[c] = w;
matrix[d] = z;
...

but the names a, b, c, d are set just at runtime.

The question is: how can i get all the keys of the matrix (i.e. a, b, c, d) and print the all matrix?

Thank you very much for your help!

   Sergio

What are a, b, c, d? Numbers or strings?

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.

Yes they are strings. Thank you very much cbkihong!

The code you posted nearly works (there were some typing errors). I post the correct code:

foreach $key1 (keys %matrix) {
        foreach $key2 (keys %{%matrix->{$key1}}) {
                print "\$matrix{$key1}{$key2} = $matrix{$key1}{$key2},  ";                            
                } 
        print"\n";                                                                                   
        }

Hope this will help sombody else.

Cheers,

 Sergio