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

Hello monks,

I would like to know what happens when I declare a variable within a loop such as my $foo within:

foreach my $a(@bar) { my $foo = &return_something($a); }

I frequently use loops with variables scoped within them and was wondering how expensive this was on memory. Am I better off declaring these variables before the block and undefining them on each iteration?
$foo must be a unique instance in memory on each iteration, how long does each instance stay in memory during this loop?
I would also like to know how to undefine a group of variables at once, other than:

($v1, $v2, $vX) = (0, 0, 0);

Can I undef ($v1, $v2, $vX); or does this only affect the first value in the array? I won't be wanting to refer to these variables outside of these blocks.
Any suggestions?

Replies are listed 'Best First'.
Re: Loops and my
by mrbbking (Hermit) on May 18, 2002 at 12:56 UTC
    Can I undef ($v1, $v2, $vX); or does this only affect the first value in the array?
    If it's an array, then you can just do @array = (); to undefine it. If they're really scalars, then you can shortcut it a little bit with $v1 = $v2 = $vX = undef;

    Example:

    #!/usr/bin/perl -w use strict; print "\nWith scalars..\n"; my ($var1, $var2, $var3) = (1, 2, 3); foreach( $var1, $var2, $var3 ){ print "$_, "; } print "\nundef them...\n"; $var1 = $var2 = $var3 = undef; foreach( $var1, $var2, $var3 ){ print "$_, "; # -w will complain about this. } print "\nWith an array..\n"; my @stuff = qw(a b c); foreach( @stuff ){ print "$_, "; } print "\nundef it...\n"; @stuff = (); foreach( @stuff ){ print "$_, "; # -w won't complain about this, because # @stuff is empty, so this line does not # execute }
Re: Loops and my
by TheHobbit (Pilgrim) on May 18, 2002 at 12:36 UTC

    Hi,
    IIRC, There is no overload. lexically scoped variables defined in a file/subroutine are keep in that file/subroutine's scratchpad and space for them is allocated at compile time.

    Cheers


    Leo TheHobbit
Re: Loops and my
by ceedee (Sexton) on May 18, 2002 at 13:06 UTC
    Thanks for the tips. Looks like I have a few more options (or more slack to hang myself with).