0

I have a Perl data structure like the following:

%hash = (
    table_id => {
        column_1_header =>
            [
                 column_value_1,
                 column_value_2,
                 column_value_3
            ],
        column_2_header =>
            [
                 column_value_4,
                 column_value_5,
                 column_value_6,
                 column_value_7,
            ],
    },
);

My goal is to produce a series of tables with each of the columns as outlined in the structure. For example:

<table id="table_id">
    <tbody>
        <tr>
            <td>column_1_header</td>
            <td>column_2_header</td>
        </tr>
        <tr>
            <td>column_value_1</td>
            <td>column_value_4</td>
        </tr>
        <tr>
            <td>column_value_2</td>
            <td>column_value_5</td>
        </tr>
        <tr>
            <td>column_value_3</td>
            <td>column_value_6</td>
        </tr>
        <tr>
            <td></td>
            <td>column_value_7</td>
        </tr>
    </tbody>
</table>

I am using Perl Dancer and Template Toolkit. What are some options to easily a table like this?

ikegami
  • 367,544
  • 15
  • 269
  • 518
indiguy
  • 505
  • 1
  • 9
  • 21
  • 2
    [`Template::Tutorial::Datafile`](https://metacpan.org/module/Template::Tutorial::Datafile#Producing-XML) will help you approach this problem – Zaid Aug 29 '12 at 19:44
  • just go through you structure and prepare table :) it's simple one. – Pavel Vlasov Aug 29 '12 at 20:00
  • 1
    @Zaid, The data is inside out compared to what that tutorial uses. While TT can handle the inside out data, it's simpler to but it right-side out first. This is what my answers shows. Creating the template is trivial after that, so I didn't bother showing it. – ikegami Aug 29 '12 at 21:58

1 Answers1

3

Change the data so it's grouped by record instead of by column.

use Algorithm::Loops qw( MapCarU );

for my $table_id (keys(%hash)) {
    my $table   = $hash{$table_id};
    my @headers = keys(%$table);
    my @recs = ( \@headers, MapCarU(sub { [ @_ ] }, @{$table}{@headers} ) );
    $hash{$table_id} = \@recs;
}

The above changes

%hash = (
    table_id => {
        col_1_header => [ val_1, val_2, val_3 ],
        col_2_header => [ val_4, val_5, val_6, val_7 ],
    },
);

to

%hash = (
    table_id => [
        [ col_1_header, col_2_header ],
        [ val_1,        val_4  ],
        [ val_2,        val_5  ],
        [ val_3,        val_6  ],
        [ undef,        val_7  ],
    ],
);

Note the the data structure does not contain enough information to recreate the original column order.

ikegami
  • 367,544
  • 15
  • 269
  • 518