|We don't bite newbies here... much|
closure clarity, pleaseby 7stud (Deacon)
|on Nov 24, 2009 at 05:14 UTC||Need Help??|
7stud has asked for the
wisdom of the Perl Monks concerning the following question:
I have a little problem:
I assume a closure is what's causing the sub to print the same output over and over again. However, the only thing I can find in the docs about closures is in relation to anonymous subs, yet this program is using a named sub.
Is the closure problem an artifact of perl trying to be efficient and not redefining the function every time through the loop? Why don't the docs mention that a named sub can create a closure? Could someone give a blow by blow description of what's happening?
That closure problem sprang up when sorting a hash inside a loop. The following program sorts two hashes by their values, which are integers. The hashes are stored in an array, so a for loop is used to step through the array. Then one hash is sorted each time through the loop, and its results are immediately displayed:
The problem can be cured by using a block with sort instead of defining a sub. This example shows that you should not be indifferent to using a block v. defining a sub when using sort().
edit: I also wanted to ask about this variation:
In that variation, the sub can't see the my variable $num. Why?