[Petal] Looping through a hash
Steve Purkis
spurkis at mkdoc.com
Thu Sep 4 18:10:20 BST 2003
On Thursday, September 4, 2003, at 03:00 pm, William McKee wrote:
> Hi all,
>
> Although the docs do not indicate that loops can only be done on
> arrays,
> my testing shows that Petal will die if you try to perform a loop over
> a hash (e.g., "Error: Not an ARRAY reference at (eval 10) line 94.").
>
> Is there a way to have Petal loop over the keys of a hash? or must I
> convert the hash into an array?
You could write a modifier, and use it with petal:repeat:
package Petal::Hash::Keys;
use strict;
use warnings;
sub process {
my ($self, $hash, $args) = @_;
my $result = $hash->fetch( $args );
die "$args is not a hash!" unless ref($result) eq 'HASH';
return [ keys %$result ];
}
1;
And then:
<span petal:repeat="key keys: $some_hash">
do something with $key ...
will this get the value: ${some_hash/$key} ?
</span>
If you want both a list of key/value pairs, you could write
Petal::Hash::Each to do something like:
return [ map { { key => $_, val => $result->{$_} } } keys %$result
];
And then:
<span petal:repeat="item each: $some_hash">
key: $item/key
val: $item/val
</span>
I've got a few little plugins like this that might be good candidates
for a Petal::Utils package at some stage.
hth,
-Steve
More information about the Petal
mailing list