in reply to Closures and Statistics

You didn't create a closure, but an anonymous subroutine. I'll try to explain in the most simple way what a closure is.

A classical example of a simple closure is that of the "multiplier generator":

sub multiplier_by { my $x = shift ; return sub { my $n = shift ; return $n * $x ; } }

Then if you run this:

my $m2 = multiplier_by(2) ; my $m3 = multiplier_by(3) ;

you will have:

my $i = 5 ; print $m2->($i) ; # prints 10 print $m3->($i) ; # prints 15 # other syntaxes for $m2, $m3 invokations allowed :-)

Now follow the execution of my $m2 = multiplier_by(2) ;: you pass a value of 2, that goes into the lexical $x and gets used in the "anonymous subroutine" definition. When the subroutine returns, you assign the return value to $m2, and here the magic happens: since you are still using it, $x is still alive somewhere in your RAM, and is accessible only inside the code inside $m2. You closed it in a cage, poor $x :-). And you have a reference to a subroutine that multiplies its argument by 2. That's your closure: ta-dah!

When you call again multiplier_by passing 3 as argument, things still work because the newly created $x has nothing in common with the previous one. So $m3 gets a reference to a subroutine that multiplies by 3 the parameter you pass to it.

I hope I made things clearer and not confused you more :-)

A note on your code: since you are declaring the variables in your subroutine with my, which is a really-good-thing-to-do, the subsequent chain of $var = 0 unless $var is superfluous as it will be always executed. You could assign a value of 0 directly in the declaration: my $var = 0 ;

Phew! I think it's better for me to stop here or my boss will fire me!

Ciao!
--bronto

# Another Perl edition of a song:
# The End, by The Beatles
END {
  $you->take($love) eq $you->made($love) ;
}