How to access perl hash value (which is an array) from Template Toolkit? -
i have assigned hash in perl follows:
my %myvers; @patches = (); @mypatches = (); foreach $myv ( @{$product->versions} ){ @patches = set_patches($myv->id); #get array of patches version foreach(@patches) { push @mypatches,@{$_}; } $myvers{$myv->name} = @mypatches; } $vars->{'myvers'} = \%myvers;
when access hash in html template code below:
[% foreach key in myvers.keys %] alert('[% key %] [% myvers.$key %]; '); [% end %]
key contains keys , $key contains number of elements in array each key assigned above.
i cannot access values of elements of array. how can ?
the problem don't store elements, store size.
$myvers{ $myv->name } = @mypatches;
assigning hash value forces scalar context, @mypatches
returns size of array. need store reference array instead:
$myvers{ $myv->name } = [ @mypatches ];
it's more common declare array inside outer loop , use reference. in fact, can skip pushing elements 1 one, can push whole array: push @mypatches, @patches
, then, don't need 2 arrays @ all:
my %myvers; $myv (@{ $product->versions }) { @patches = set_patches($myv->id); $myvers{ $myv->name } = \@patches; } $vars->{myvers} = \%myvers;
or, if want laconic:
$myvers{ $_->name } = [ set_patches($_->id) ] @{ $product->versions };
Comments
Post a Comment