Template::Iterator - Data iterator used by the FOREACH directive
my $iter = Template::Iterator->new(\@data, \%options);
It may be used as the base class for custom iterators.
my $iter = Template::Iterator->new([ 'foo', 'bar', 'baz' ]);
The constructor will also accept a reference to a hash array and will expand it into a list in which each entry is a hash array containing a 'key' and 'value' item, sorted according to the hash keys.
my $iter = Template::Iterator->new({
foo => 'Foo Item',
bar => 'Bar Item',
});
This is equivalent to:
my $iter = Template::Iterator->new([
{ key => 'bar', value => 'Bar Item' },
{ key => 'foo', value => 'Foo Item' },
]);
When passed a single item which is not an array reference, the constructor will automatically create a list containing that single item.
my $iter = Template::Iterator->new('foo');
This is equivalent to:
my $iter = Template::Iterator->new([ 'foo' ]);
Note that a single item which is an object based on a blessed ARRAY references will NOT be treated as an array and will be folded into a list containing that one object reference.
my $list = bless [ 'foo', 'bar' ], 'MyListClass';
my $iter = Template::Iterator->new($list);
equivalent to:
my $iter = Template::Iterator->new([ $list ]);
If the object provides an as_list() method then the Template::Iterator constructor will call that method to return the list of data. For example:
package MyListObject;
sub new {
my $class = shift;
bless [ @_ ], $class;
}
package main;
my $list = MyListObject->new('foo', 'bar');
my $iter = Template::Iterator->new($list);
This is then functionally equivalent to:
my $iter = Template::Iterator->new([ $list ]);
The iterator will return only one item, a reference to the MyListObject object, $list.
By adding an as_list() method to the MyListObject class, we can force the Template::Iterator constructor to treat the object as a list and use the data contained within.
package MyListObject;
...
sub as_list {
my $self = shift;
return $self;
}
package main;
my $list = MyListObject->new('foo', 'bar');
my $iter = Template::Iterator->new($list);
The iterator will now return the two item, 'foo' and 'bar', which the MyObjectList encapsulates.
<http://www.andywardley.com/|http://www.andywardley.com/>
Copyright (C) 1996-2004 Andy Wardley. All Rights Reserved. Copyright (C) 1998-2002 Canon Research Centre Europe Ltd.
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
|
Закладки на сайте Проследить за страницей |
Created 1996-2025 by Maxim Chirkov Добавить, Поддержать, Вебмастеру |