1

我有以下问题:我有一组对哈希的引用,我想渲染它。

$VAR1 = \{
        'nice_key' => undef,
        'nicer_key' => '0',
        'nicest_key' => 'Miller'
      };
$VAR2 = \{
        'nice_key' => undef,
        'nicer_key' => '0',
        'nicest_key' => 'Farns'
      };
$VAR3 = \{
        'nice_key' => undef,
        'nicer_key' => '0',
        'nicest_key' => 'Woodstock'
      };
...

我将其传递\@tablerows给模板。在我做的模板里面:

[% FOREACH row = tablerows %]
    <tr>
        <td>[% row %]</td>
        <td>[% row.nicer_key %]</td>
        <td>[% row.nicest_key %]</td>
    </tr>
[% END %]

-line 输出类似的[% row %]东西REF(0x74a0160),但其他两行只是空白。

据我了解,row模板中的变量必须取消引用才能调用row.nicer_key,但使用->or{}会导致解析器错误。

这甚至可能还是我做错了什么?

编辑:数据结构的背景:程序执行以下操作:

  1. 解析包含表格的 HTML 文件
  2. 在解析时,将表的每一行读入一个哈希(nice_keys 是表的单元格)并将这些哈希存储到一个哈希的哈希中(让我们称之为tabledata
  3. 做一些数据库查询并将这些添加到内部哈希中(例如nicest_key,原始 HTML 文件中不存在)
  4. 以与之前相同的顺序输出一个 HTML 表格。

为了保持原始表的顺序,我tablerows在第 2 步中用对内部哈希的引用填充了数组。

Edit2:我的意图是: 在此处输入图像描述

箭头表示对哈希的引用。

我如何填写这些数据

my %tabledata = ();
my @tablerows = ();
foreach (... parsing ...) {
  ...
  $tabledata{$current_no} = ();
  push @tablerows, \$tabledata{$current_no};

  $tabledata{$current_no}{$row} = $value;
}

当我转储它们中的每一个%tabledata并且@tablerows内容对我来说似乎是正确的。

4

2 回答 2

3

正如评论所说(当我写这篇文章时你自己发现了),你的核心问题是你的哈希被埋得太深了一个多余的引用级别。你应该首先努力解决这个问题。

现在回答帖子标题中的实际问题,AFAIK 模板工具包本身并没有提供强制哈希取消引用的工具,但添加一个是可行的:

my @array = ( \{ nice_key => undef, nicer_key => '0', nicest_key => 'Miller'} );

Template->new->process( \<<EOT, { deref => sub{${+shift}}, tablerows => \@array } );
[% FOREACH row = tablerows %]
    <tr>
        <td>[% row %]</td>
        <td>[% deref(row) %]</td>
        <td>[% deref(row).nicer_key %]</td>
        <td>[% deref(row).nicest_key %]</td>
    </tr>
[% END %]
EOT

我实际上试图将其实现为标量 vmethod 并失败了。任何指针?

于 2013-08-29T10:41:27.433 回答
1

好的,我发现了问题:

$tabledata{$current_no} = ();
push @tablerows, \$tabledata{$current_no};

在我的代码中,现在我有了

$tabledata{$current_no} = {};
push @tablerows, $tabledata{$current_no};

这意味着,我有一个散列引用而不是散列上下文中的列表可以使用,结果证明这就是我想要的。

这会导致以下转储(注意,没有对引用的引用)并且模板被正确解析。

$VAR1 = {
    'nice_key' => undef,
    'nicer_key' => '0',
    'nicest_key' => 'Miller'
  };
$VAR2 = {
    'nice_key' => undef,
    'nicer_key' => '0',
    'nicest_key' => 'Farns'
  };
$VAR3 = {
    'nice_key' => undef,
    'nicer_key' => '0',
    'nicest_key' => 'Woodstock'
  };
...
于 2013-08-29T10:20:07.183 回答