Hi,
as a side note, your anonymous function does not really act as a closure:
my $fh = IO::File->new($filename, 'r'); my $fh_iterator = sub { my $fh = shift; my $line = $fh->getline; } while (my $line = $fh_iterator->($fh)) { # do stuff to $line }
because you are passing $fh each time to the sub (and you have to, you actually get a fresh copy of $fh each time the anonymous subroutine is called).
If you want it to act as a closure, you may do something like this (untested):
sub create_iterator{ my $filename = shift; my $fh = IO::File->new($filename, 'r'); return sub { my $line = $fh->getline; } } my $fh_iterator = create_iterator($file_name); while (my $line = $fh_iterator->()) { # do stuff to $line }
Now, $fh is really a persistent variable within the sub scope, this is a real closure.
In reply to Re: Iterator to parse multiline string with \\n terminator
by Laurent_R
in thread Iterator to parse multiline string with \\n terminator
by three18ti
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |