Just another Perl shrine | |
PerlMonks |
Re: how to sum over rows based on column headings in perlby roboticus (Chancellor) |
on Jul 29, 2015 at 20:49 UTC ( [id://1136789]=note: print w/replies, xml ) | Need Help?? |
I'd suggest building an array to map column number to the column name, which it looks like you may be doing. I'd also suggest using a hash to act as your accumulator: the key would be the column name (G1, G2, G3). Then the procedure would be something like this:
So lets see how it would work with this input data:
So we first create a hash to hold your counters, starting like { } So we read the first line, and find it's a header, so we build a column number to name map, resulting in the map: 1-->G1, 2-->G1, 3-->G2, 4-->G3, 5-->G3, then go to the next line. For the second line, we split it into columns. The first column (column 0) will be the name of the counter in our hash. So let's scan through the columns for interesting values: Column 1 has 'W' so it's boring and we skip over it. Column 2 has an 'M', so we want to count it. So we consult our column to name table, and find that column 2 maps to G1. So we update the counter slot for Gname=A, Colheader G1 to 1. Column 3 also has a 'M', and column 3 maps to G2, so update counter for A/G2 to 1. The remaining columns are 'W', so we ignore them. We split the next line up and find that it's the same Gname (A). Working through the columns, we see that the interesting columns are 1, 4 and 5, which map to G1, G3 and G3. So the A/G1 counter increases to 2, the A/G2 counter increases to 2 also. The A/G3 counter is set to 1. The final line gives us a new Gname, B. It's interesting columns are 1, 3, 4 and 5, which map to G1, G2, G3 and G3 respectively. So we set both B/G1 and B/G2 to 1, and B/G3 to 2. So our final counter hash shows that for those three rows, we would have:
Update: Added the "Create a hash" line to show where it should be created, and then the worked out example. ...roboticus When your only tool is a hammer, all problems look like your thumb.
In Section
Seekers of Perl Wisdom
|
|