http://www.perlmonks.org?node_id=1057132


in reply to Re: Iterator to parse multiline string with \\n terminator
in thread Iterator to parse multiline string with \\n terminator

What exactly makes it not a closure? Is it that I'm passing a variable each time? If it was a new copy of $fh, wouldn't $fh_iterator->($fh) always return the same line (since it's creating a copy of the $fh object, on next passing it would be a copy of the original)?

Thanks for setting me straight, I always like learning new things.

  • Comment on Re^2: Iterator to parse multiline string with \\n terminator

Replies are listed 'Best First'.
Re^3: Iterator to parse multiline string with \\n terminator
by Laurent_R (Canon) on Oct 06, 2013 at 09:29 UTC

    $fh is a file handler, i.e. it is actually an iterator on a file, so that each time you read from $fh, you get the next line. In your sub, your my $fh = shift; actually creates a new copy of $fh each time the sub is called. It still works because $fh "knows" which is the next line to read from the file. But your anonymous sub is not a closure; the alternative code I wrote is actually keeping its own copy of $fh, my anonymous sub actually closes on $fh. Please note that an anonymous function is not necessarily a closure, and a closure does not necessarily have to be anonymous (although is is often the case).

    You might want to have a look to this: Closure on Closures.

      Awesome! Thanks for the info and link.