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

There're different ways to emulate a numeric matrix (or N-dimenson one for that matter) with row and column labels (i.e. data being accessed with array indexes but having (row and column) labels associated with them), such as using Text::Column with an ordered hash, etc.

Is there one module that does the whole thing? Just somehow failed to locate one.

Thanks.
  • Comment on Numeric matrix w/ textual row/column labels

Replies are listed 'Best First'.
Re: Numeric matrix w/ textual row/column labels
by BrowserUk (Patriarch) on Jul 10, 2003 at 01:19 UTC

    If I'm reading you right, you want to access a 2D array using textual indices. Something like this

    #! perl -slw use strict; require 5.008; # For use constant %hash syntax. use constant { LONDON => 0, PARIS => 1, TOKYO => 2, NEW_YORK => 3, MILAN => 4, SAN_PAULO => 5, }; use constant { FIRST_QUARTER => 0, SECOND_QUARTER => 1, THIRD_QUARTER => 2, FOURTH_QUARTER => 3, TOTAL => 4, }; my @sales = map{ [ map{ int(rand(10000))/100 } FIRST_QUARTER .. FOURTH_QUARTER ] } LONDON .. SAN_PAULO; for my $city ( LONDON .. SAN_PAULO ) { $sales[ $city ][ TOTAL ] += $sales[ $city ][ $_ ] for FIRST_QUARTE +R .. FOURTH_QUARTER; } print "@{ $sales[ $_ ] }[ FIRST_QUARTER .. TOTAL ]" for LONDON .. SAN_ +PAULO;

    The upside is that the constants get translated in-line which is good for efficiency. The downside is that you can't (easily) use them to generate text for display.


    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller


Re: Numeric matrix w/ textual row/column labels
by Zaxo (Archbishop) on Jul 10, 2003 at 01:07 UTC

    There is a deprecated data structure called a pseudohash which is ideal for this, whatever its other disadvantages. To pseudohashify your AoA:

    my $AoA = [ [1..3], [7..9], [3..5] ]; my $row_labels = { foo => 1, bar => 2, baz => 3 }; my $col_labels = { do => 1, re => 2, mi => 3 }; unshift @$_, $col_labels for @$AoA; unshift @$AoA, $row_labels; print $AoA->{'foo'}{'re'}, $/; print $AoA->[1][2], $/;
    This is not well-regarded these days, but it will do the job. Don't rely on it being available in a year or two.

    After Compline,
    Zaxo