madM has asked for the wisdom of the Perl Monks concerning the following question:

Hi all! i wrote this code and now i want to convert my matrix into and array of arrays so that will be easear for me to work with.. do you have any suggestions?
while (my $key1 = shift @keys) { ##enters loop 2 alignments at the t +ime foreach my $key2 (@keys) { $seq1 =$sequences->{$key1}; $seq2 =$sequences->{$key2}; LINE: for (my $i=0; $i< length $seq1; $i++){ my ($substr1,$substr2) = (substr($seq1,$i,1),substr($seq2, $i, +1)); next LINE if ("$substr1$substr2" =~ /-/); if("$substr1$substr2"=~ /[^@aminos]/){ $else->{$substr1}->{$substr2}+=1; $else->{$substr2}->{$substr1}+=1; next LINE; } if ($substr1 eq $substr2){ $matrix->{$substr1}->{$substr2}++; $eq->{$substr1}++; }elsif ($substr1 ne $substr2){ $matrix->{$substr1}->{$substr2} += 1/2; $matrix->{$substr2}->{$substr1} += 1/2; } } } } print " A C D E F G H I K L M N + P Q R S T V W Y\n\n"; foreach my $key (sort keys %$matrix){ print $key." "x2; foreach my $key2 (sort keys %{$matrix->{$key}}){ printf("%3d ", $matrix->{$key}->{$key2}); } print "\n"x2; }

Replies are listed 'Best First'.
Re: converting a hash based matrix into an array based matrix
by Athanasius (Cardinal) on Aug 12, 2013 at 17:22 UTC

    A quick observation:

    while (my $key1 = shift @keys) {

    is a potential bug. Consider what happens when @keys contains an element that Perl considers “false”:

    3:19 >perl -wE "my @keys = ('a'..'c', '0', 'd'..'f'); say ''; while ( +my $key = shift @keys) { print qq[$key: ]; for (@keys) { print qq[$_ +] } say '' }" a: b c 0 d e f b: c 0 d e f c: 0 d e f 3:19 >

    Better to play it safe by testing the size of the array before using shift:

    3:19 >perl -wE "my @keys = ('a'..'c', '0', 'd'..'f'); say ''; while ( +@keys) { my $key = shift @keys; print qq[$key: ]; for (@keys) { print + qq[$_ ] } say '' }" a: b c 0 d e f b: c 0 d e f c: 0 d e f 0: d e f d: e f e: f f: 3:19 >

    madM, I know this doesn’t address your question, but it may just save you some debugging down the track.

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re: converting a hash based matrix into an array based matrix
by SuicideJunkie (Vicar) on Aug 12, 2013 at 17:25 UTC

    Why was the matrix put in as a hash in the first place? If you have a large, sparse matrix, then moving to an array could be quite expensive.

    One of my sayings is that the best way to clean up a mess is to not make one in the first place. For data structures, the best way to convert is to build the final structure from the beginning if possible.

    If those keys are fixed as the print on line 29 suggests, you could make a hash that maps ' '=>0, A=>1, C=>2, etc. Then use it somewhat like:$matrix->[$indexfor{$key}][$indexfor{$key2}] ++;