I have assigned a hash in perl as follows:
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:
[% 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.
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. 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:
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 };
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.