Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??


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

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

    What's my password?
    Create A New User
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others taking refuge in the Monastery: (4)
    As of 2020-01-27 08:46 GMT
    Find Nodes?
      Voting Booth?