in reply to Garbage-collecting with closures

Not all closures leak memory. Here's an example of a situation that does leak:
my $foo; sub leaky { my $closure = sub { $foo++ }; }
That will create a new copy of $foo every time and it will not get cleaned up. I don't know if 5.8 did anything to address this or not.

Replies are listed 'Best First'.
Re2: Garbage-collecting with closures
by dragonchild (Archbishop) on Feb 19, 2003 at 23:25 UTC
    Does that complain under strict? I tried the following:
    use strict; my $foo = 0; sub leaky { my $closure = sub { $foo++ }; return $closure; } my $x = leaky(); my $y = leaky(); print $y->(), $/ while $x->() < 10; ---- 1 3 5 7 9
    The output seemed to be correct ...

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

      The output is correct, but it eats up memory. If you keep looping on that sub, your machine will go into swap.
Re: Re: Garbage-collecting with closures
by Courage (Parson) on Feb 20, 2003 at 08:53 UTC
    It does not leaks memory for me. Why should it?

    I tried

    my $foo; sub leaky { my $closure = sub { $foo++ }; } for (;;) {leaky}
    for quite a long time and saw usage of constant memory.

    Courage, the Cowardly Dog

      Sorry, my mistake. They have to be nested anonymous subs, like this:
      my $foo = 'asdf' x 1000; for (1..900000) { my $outer_sub = sub { my $inner_sub = sub { $foo }; } }
        You're right.

        I think this code should be fed to 'perlbug' utility.

        Although I seem to remember it was discussed in p5p list somehow, such closure leaks were almost went away just before 5.6.0, but they were too evil to fix.

        Courage, the Cowardly Dog