perlquestion
mr.dunstan
This has been a hot topic at my workplace and my boss came up with this example for showing how closures work.
<code>
#!/usr/local/bin/perl
use strict;
my $dave = new Foo ("dave", "oranges", "grapefruit");
$dave->("debug message");
package Foo;
sub new {
my ($class, @stuff) = @_;
return sub { doit(@stuff, @_) }; # <-- closure here?
}
sub doit {
print shift, ": ", join(",", @_), "\n";
}
</code>
Prepare to correct me if I'm wrong - I think what we've got here is a constructor (sort of) that returns a reference to an anonymous subroutine. When we call new() we're also setting $class and @stuff in the namespace of that anonymous subroutine to be "dave" and ("oranges", "grapefruit") respectively. <br><br>
When I run this thing I get:<br><br>
dave: oranges,grapefruit,debug message <br>
<br>
Ok, so this is kind of neat, now I understand how you can use one constructor and some properties in order to respond with a reference to an anonymous subroutine of your choosing, but what I'm curious about is - is this -really- a closure?
<br><br>
I'm not completely versed in how long values like $class and @stuff would live inside a sub - only for the duration of the execution of the sub, right? <br><bR>
The closure (or rather using those values in the anonymous sub) makes these values live on past the execution of the sub, right? <br><br>
Super Confused, -mr.dunstan