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

I have the following arrays with different lengths that I want to map them with the same key.
# Week numbers, 8 columns @headers = ("2011-34", "2011-35", "2011-36", "2011-37", "2011-38", "20 +11-39", "2011-40", "2011-41"); %data = ("2011-34", BCE, "2011-35", YZA, "2011-36", MID, "2011-37", KAL, "2011-39", WUL, "2011-41", YOK); # Need to map output as below: | |2011-34|2011-35|2011-36|2011-37|2011-38|2011-39|2011-40|2011-41| | 1 | BCE | YZA | MID | KAL | | WUL | + | YOK |
Can someone here help? Thanks in adance !

Replies are listed 'Best First'.
Re: Need Help Mapping Arrays
by Eliya (Vicar) on Aug 23, 2011 at 15:47 UTC
    I have the following arrays with different lengths

    Actually, you have one array and a hash. This means you can do a simple lookup for each element of the array (i.e. $data{$element} ).

    The following snippet would, for example, produce the output you want:

    # ... data declarations as you have it (but with values "BCE" etc. quo +ted) print "| |", (map sprintf(" %8s |", $_), @headers), "\n"; + # print column headers print "| 1 |", (map sprintf(" %8s |", $data{$_}||""), @headers), "\n"; + # print row of data __END__ | | 2011-34 | 2011-35 | 2011-36 | 2011-37 | 2011-38 | 2011-39 +| 2011-40 | 2011-41 | | 1 | BCE | YZA | MID | KAL | | WUL +| | YOK |

    P.S. please put <c> ... </c> around code sections of your post. This makes it easier to read.

      Couldn't you dump the header array altogether and just load a single hash? You could sort the keys, if you needed the order fixed. (or use Tie::IxHash for key ordering)
Re: Need Help Mapping Arrays
by locked_user sundialsvc4 (Abbot) on Aug 24, 2011 at 12:49 UTC

    I would use an array of hashrefs, because you know you’re going to have a certain number of rows whether those rows are empty or filled.

    Another trick is to capture the column-headings as you encounter them.   A hash is very handy for this.   If you simply do $$keys_encountered{$heading} = 1; along the way, you can use sort keys(%$keys_encountered) to read all of the column headings you actually encountered, in alphabetic order.   (In this case, the value of the hash entry is unimportant; you care about the presence of the key.)