On 12-03-22 05:23 PM, Chris Stinemetz wrote:
but I not real sure how to begin. Any
help is greatly appreciated.

Below is the input data:

Hr 12
0001 2
0002 3
0003 1
Hr 13
0001 2
0002 3
0003 1
Hr 14
0001 2
0002 3
0003 1

Desired output below:

           12 13 14
0001    2   2  2
0002    3   3  3
0003    1   1  1

The first question you should ask yourself when you need to write a script that manipulates data is: Is preserving the input order of the data important? If so, the using an array is the easiest way to do this. In this case, however, the objective is to rearrange the data, so we are free to use any data structure to hold the data.

The second question is: What is the best data structure for this task? The possibilities fall into three categories: one similar to the input structure, one similar to the output, and some intermediate one. The advance of the first is that it will take little processing of the input to achieve it but more processing of the output. The second choice is the same as the first but with input and output switched around. The third is the most complex and should only be used as a last resort. But of the first two, which is better?

Well, take a look at the structures of the data. The input is linear; it has one datum after another. The output is a table, two dimensional. If we store the data in a linear structure, like its input, we would still have to transform it to a two-dimensional one before we can output it. But if we can transform the input into a two-dimension structure, it can be easily outputted and we save ourselves a step. So, since preserving input order is not important, a hash of hashes seems the best structure.

When printing out a table, it's nice to have the column index or key as the inner one and the row index or key as the outer one. The column key is the Hr value, and the row key is from the lines with two numbers. So, the pseudo-code looks like this:

Create a variable to hold the Hr key;
For each line of input:
    If the line starts with Hr:
        Save the number in the Hr variable;
    Else
        Extract the key and value from the line;
        Store it in a HoH with this key, the Hr key and the value
            $HoH{$key}{$Hr_key} = $value;

Now output the table (exercise left to the reader) :).


--
Just my 0.00000002 million dollars worth,
  Shawn

Programming is as much about organization and communication
as it is about coding.

[edited for today's programmers]
"Show me your code and conceal your interfaces, and I shall continue
to be mystified. Show me your interfaces, and I won't usually need
your code; it'll be obvious."
        -- Fred Brooks

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to