in reply to Closures as Itterators

Two suggestions:
  1. Get in the habit of using the 'other' notation for instantiating an object:
    my $fh = IO::File->($datafile) or die; #instead of - and you don't need the quotes either my $fh = new IO::File "$datafile";
    The reason is because is purely habit. One day you will write your own classes, and they may use inheritance, which is where the other style will bit you. Tis a shame i think, because it just _looks_ so much nicer. ;)

  2. In the while loop inside the closure, why not just use this:
    while (<$fh>) { chomp; # use $_ instead of $row # etc . . .
    Now you don't need the last, and while(1) just looks evil. >:)

Otherwise, nice i like it. Damian Conway discusses using closures to implement iterators in his awesome OO book. You can find a snippet at (jeffa) Re: Defining Arrays.

Jeff

R-R-R--R-R-R--R-R-R--R-R-R--R-R-R--
L-L--L-L--L-L--L-L--L-L--L-L--L-L--

Replies are listed 'Best First'.
Re: (jeffa) Re: Closures as Itterators
by blakem (Monsignor) on Jul 01, 2001 at 14:38 UTC
    I've read elsewhere about subtleties with the instantiation syntax I used (I think it was on a python propaganda page) Easy enough to change.

    The loop construct, however, is a bit strained. I don't really want to clobber $_, but I do like:

    while(chomp($row = <$fh>)) {
    Much better than:
    while(1) { chomp($row = <$fh>) or last;
    I have Damians book, but only made it about half way through before losing the thread. I don't do much OO programming, so I didn't have many concrete examples to toy with while reading the book. It was very well written though, got much further than any other OO book I've tried.

    -Blake

      To avoid clobbering $_, it's quite easy to just do something like:

      sub thingy { # blah blah blah... local $_; while (<$fh>) { chomp; # do stuff here... } # more stuff here... }

      In fact, I do that with every package function I write, even if I don't intend on using $_ explitly, because I don't want to depend on a built-in function not clobbering $_ for me in an attempt to be helpful.

      Furthermore, the while(chomp($row=<$fh>)) syntax is very dangerous. It will miss the last line of a file, if that line doesn't end with a newline. The while() loop is dependent on the return of something from chomp, not the definedness of $row. I would definitely use something like:

      while (defined(my $row = <$fh>)) { chomp $row; # stuff here... }
        I know what while(chomp($row = <$fh>)) is doing. In this case, though, I'm reading from a very specific data file (which does end with a newline) and the very nature of the routine prevents it from using the last line of the data file 99.9% of the time anyway. (is is primarily used to grab a few lines from the middle of the file)
        Thanks for the $_ tip, though, I like it.

        -Blake