data/TWiki/TWikiLineIteratorDotPm.txt
author Colas Nahaboo <colas@nahaboo.net>
Sat, 26 Jan 2008 15:50:53 +0100
changeset 0 414e01d06fd5
permissions -rw-r--r--
RELEASE 4.2.0 freetown
colas@0
     1
---+ Package =TWiki::LineIterator=
colas@0
     2
colas@0
     3
Iterator over the lines in a file
colas@0
     4
colas@0
     5
colas@0
     6
%TOC%
colas@0
     7
colas@0
     8
---++ new( $file )
colas@0
     9
colas@0
    10
Create a new iterator over the given file. if the file cannot be opened, then
colas@0
    11
there will be no elements in the iterator.
colas@0
    12
colas@0
    13
colas@0
    14
---++ hasNext() -> $boolean
colas@0
    15
colas@0
    16
Returns false when the iterator is exhausted.
colas@0
    17
colas@0
    18
<verbatim>
colas@0
    19
my $it = new TWiki::ListIterator(\@list);
colas@0
    20
while ($it->hasNext()) {
colas@0
    21
   ...
colas@0
    22
</verbatim>
colas@0
    23
colas@0
    24
colas@0
    25
---++ next() -> $data
colas@0
    26
colas@0
    27
Return the next line in the file.
colas@0
    28
colas@0
    29
The iterator object can be customised to pre- and post-process entries from
colas@0
    30
the list before returning them. This is done by setting two fields in the
colas@0
    31
iterator object:
colas@0
    32
colas@0
    33
   * ={filter}= can be defined to be a sub that filters each entry. The entry
colas@0
    34
     will be ignored (next() will not return it) if the filter returns false.
colas@0
    35
   * ={process}= can be defined to be a sub to process each entry before it
colas@0
    36
     is returned by next. The value returned from next is the value returned
colas@0
    37
     by the process function.
colas@0
    38
colas@0
    39
For example,
colas@0
    40
<verbatim>
colas@0
    41
my $it = new TWiki::LineIterator("/etc/passwd");
colas@0
    42
$it->{filter} = sub { $_[0] =~ /^.*?:/; return $1; };
colas@0
    43
$it->{process} = sub { return "User $_[0]"; };
colas@0
    44
while ($it->hasNext()) {
colas@0
    45
    my $x = $it->next();
colas@0
    46
    print "$x\n";
colas@0
    47
}
colas@0
    48
</verbatim>
colas@0
    49