简体   繁体   English

从Perl数据结构打印表

[英]Printing a Table from a Perl Data Structure

I have a Perl data structure like the following: 我有一个如下的Perl数据结构:

%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. 我正在使用Perl Dancer和模板工具包。 What are some options to easily a table like this? 像这样的表格有哪些选择?

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. 请注意,数据结构包含的信息不足,无法重新创建原始的列顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM