toniax has asked for the wisdom of the Perl Monks concerning the following question:

Thanks for all your answers and links . I am clear on lexical variables now.

Hello,
Say I have a program with 4 subs in it and one of the subs has --my $var-- set to something.
Will this var get cleaned after the sub is finished?
Will it only get cleaned after the whole program is finished ?
Will setting $| = 1; clear this var ?

Replies are listed 'Best First'.
Re: my $var
by ikegami (Patriarch) on Nov 10, 2010 at 19:29 UTC

    A lexical (my) variable get cleared when exiting the tightest lexical scope (curlies or file) in which it is found.

    sub f { my $x = ...; { my $y = ...; ... # $y cleared here. } ... # $x cleared here. }

    It doesn't matter how the scope is exited. It'll get cleared on return, die, next, etc.

    You obviously didn't read the documentation for $|.

Re: my $var
by superfrink (Curate) on Nov 10, 2010 at 19:31 UTC
Re: my $var
by Anonymous Monk on Nov 10, 2010 at 19:40 UTC
Re: my $var
by Anonymous Monk on Nov 10, 2010 at 19:34 UTC
    A lexical variable -- a variable declared with my -- exists only while the scope its in is currently being executed. Perl uses reference counting for "garbage collection", if that helps you visualize the process.

    The global, built-in variable $| allows you to turn on or off autoflush on the currently-selected output channel (STDOUT by default). This has nothing to do with lexical variables.