简体   繁体   English

如何从模板工具箱访问perl哈希值(是一个数组)?

[英]How to access perl hash value (which is an array) from Template Toolkit?

I have assigned a hash in perl as follows: 我在perl中分配了一个哈希,如下所示:

my %myvers;
my @patches = ();
my @mypatches = ();

foreach my $myv ( @{$product->versions} ){

@patches = set_patches($myv->id);   #get the array of patches for the version
foreach(@patches) {
    push @mypatches,@{$_};
    }
$myvers{$myv->name} = @mypatches;
}

$vars->{'myvers'} = \%myvers;

When I access the hash in html template with the code below: 当我使用以下代码访问html模板中的哈希值时:

[% FOREACH key IN myvers.keys %]
alert('[% key %] is [% myvers.$key %]; ');
[% END %] 

key contains the keys and $key contains the number of elements in the array for each key assigned above. key包含键, $ key包含上面分配的每个键的数组中的元素数。

I cannot access the values of elements of the array. 我无法访问数组元素的值。 How can I do that ? 我怎样才能做到这一点 ?

The problem is you don't store the elements, you only store the size. 问题是您不存储元素,仅存储大小。

$myvers{ $myv->name } = @mypatches;

Assigning to a hash value forces a scalar context, so @mypatches returns the size of the array. 分配给哈希值会强制执行标量上下文,因此@mypatches返回数组的大小。 You need to store a reference to the array instead: 您需要存储对数组的引用:

$myvers{ $myv->name } = [ @mypatches ];

It's probably more common to declare the array inside the outer loop and use a reference. 在外部循环中声明数组并使用引用可能更常见。 In fact, you can skip pushing the elements one by one, as you can push the whole array: push @mypatches, @patches , but then, you don't need two arrays at all: 实际上,您可以跳过一个元素一个一个地推送元素,因为您可以推送整个数组: push @mypatches, @patches ,但是然后,您根本不需要两个数组:

my %myvers;

for my $myv (@{ $product->versions }) {
    my @patches = set_patches($myv->id);
    $myvers{ $myv->name } = \@patches;
}

$vars->{myvers} = \%myvers;

or, if you really want to be laconic: 或者,如果您真的想简洁:

$myvers{ $_->name } = [ set_patches($_->id) ] for @{ $product->versions };

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

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