in reply to Re^2: Garbage collection at subroutine return
in thread Garbage collection at subroutine return

Hi tcarmeli,

You don't need to have it global, just have it scoped outside the sub.

For example:

{ my %myhash; sub DoIt{ my $limit=shift; my $i; # really, what you'd do here is just init the # as-yet uninitialized part foreach $i ((scalar keys %myhash)..$limit){ $myhash{$i}=1; } $func_done = (times)[0]; return; } } # scope for %myHash
Of course, I haven't tried this, but I think it'd do what you want, and handle the case where it's called twice with different values of $limit.

Mike

Replies are listed 'Best First'.
Re^4: Garbage collection at subroutine return
by derby (Abbot) on Feb 15, 2007 at 17:26 UTC

    No need to really even do that. Use references and have DoIt return the reference:

    my $h = DoIt( $max ); sub DoIt{ my $limit=shift; my $i; my $myhash; foreach $i (0..$limit){ $myhash->{$i}=1; } $func_done = (times)[0]; $myhash; }
    That prevents the reference count from being decremented and hence no gc (well at least tell the end of the block containing $h)

    -derby
      True, but slightly different.

      Your approach is correct if the goal is to construct a one-off structure and pass it back to the caller, surviving until the caller is done with it. Useful if the function generates some kind of custom hash mapping, for example.

      My approach is correct if the intent of myhash is to be some kind of persistent structure internal to the mechanics of DoIt, perhaps some kind of memoization cache or other internal structure.

      They're both useful, it all depends on what the original intent was (which is a bit hard to discern from the question).


      Mike