in reply to Strange memory growth?

the if block is no lexical block like the blocks you declare for while, for, foreach, etc. so the $foo scalar lives in the whole script.

Replies are listed 'Best First'.
Re: Re: Strange memory growth?
by fletcher_the_dog (Friar) on Nov 07, 2003 at 21:10 UTC
    Um, that is not true, and if it was then it is more likely that the memory growth would not happen because $foo would be overwritten each time.
    use strict; if (1) { my $foo = "hi"; } print $foo."\n"; __OUTPUT__ Global symbol "$foo" requires explicit package name at scope.pl line 5 +. Execution of scope.pl aborted due to compilation errors.
      me stupid, you are absolutely right fletcher.
Re: Re: Strange memory growth?
by mrpeabody (Friar) on Nov 07, 2003 at 21:27 UTC
    Wrong. Lexical variables declared inside an if BLOCK are not visible outside that block (and its associated else/elsif BLOCK). perlsub:
    The "my" operator declares the listed variables to be lexically confined to the enclosing block, conditional ("if/unless/elsif/else"), loop ("for/foreach/while/until/continue"), subroutine, "eval", or "do/require/use"'d file.
    As can be seen:
    502 $ perl -we'use strict;if(1){my $foo="foo"};print $foo' Global symbol "$foo" requires explicit package name at -e line 1. Execution of -e aborted due to compilation errors.
    The scoping rules work as they should, but the memory usage could definitely be more conservative.

    edit: beaten

Re: Re: Strange memory growth?
by pg (Canon) on Nov 07, 2003 at 21:20 UTC

    This is still a bug. Try this:

    use strict; use warnings; if (1) { my $a = 100; } print $a;

    If you are not allowed to ref that $a any more, once exit that if block, there is absolutely no point not to garbage collect it.

      there is absolutely no point not to garbage collect it

      Yes there is. It might be cheaper, (read: Lazier) to not garbage collect it at all, and just let the program fall off the end of the world. Just because you can, doesn't mean it's worth spending the effort to do so.

      It was only with the advent of mod_perl and similar long-running persistent perl processes that any serious effort started to be devoted to keeping track of perl's resource usage. It used to be that it was cheaper not to do anything, because in a few milliseconds time, the pages used by the process would be reclaimed by the OS when program ended anyway.

      And given perl's propensity for trading off memory for speed, it doesn't really surprise me that we see the behaviour demonstrated by the OP.