in reply to Re: Closures and callbacks...
in thread Closures and callbacks...

I'd like to point out that these aren't really closures...
The read_row function is a closure, it just happens to be a non-encapsulated closure as process can also see @indexes. It would act as a more effective closure if it was re-structured like so
use Symbol; { my @indexes = qw (3 0 4 5 6 7); my $fh = gensym; open $fh,"<my.dat" or die "my.dat: $!"; sub read_row { my $row = <$fh>; close $fh and return unless defined($row); return (split(/\s+/,$row))[@indexes]; } }

HTH

_________
broquaint

Replies are listed 'Best First'.
Re: Re: Re: Closures and callbacks...
by zigdon (Deacon) on Oct 23, 2002 at 12:17 UTC

    I'm still very new to closures, but I just don't get it. Why is read_row a closure? Doesn't read_row just return a list of values, instead of code?

    -- Dan

      Why is read_row a closure?
      Because it is saving lexical state by referring to a lexical variable that is above the immediate lexical state. So if you call main::read_row from another package that isn't in the same lexical scope as read_row, it will still work even though @indexes is no longer in scope. This is because the lexical variable @indexes was saved by read_row, ergo, it is a closure. I hope that makes as much sense as I think it does. Hopefully (time forbidding) I'll write up a closure tutorial so I can merlyn any future closure questions ;)
      Doesn't read_row just return a list of values, instead of code?
      Returning an anonymous sub does not define a function as a closure, see the above explanation for why read_row qualifies as a closure.
      HTH

      _________
      broquaint