in reply to Two Questions on "my"

Much of the work you're trying to avoid is done anyway when the braces define a scope. Generally, the idea is to use scoping to get rid of knowledge where it's unneeded. I'd use the second form in question one because $foo is then undefined afterwards. Similarly for question two, get rid of the declaration outside the loop.

If you must, you can make the exterior declaration and then say ($key, $value) = returnsAnArray(); inside the loop. I think the loops would be better written as { my $i = 0; while ($i++ < $a_big_number) { ... }} rather than the C-style for loops you have. You could also say for (0..$a_big_number) { ... }, but that is no way to save memory.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re: Re: Two Questions on "my"
by Somni (Friar) on May 22, 2004 at 23:13 UTC

    > You could also say for (0..$a_big_number) { ... }, but that is no way to save memory.

    Actually, it is. For some time now that style of foreach loop has been optimized. It doesn't create a list of $a_big_number+1 elements; it efficiently iterates one at a time through the set, much as the equivalent C-style for loop would.

    You can prove this to yourself by using a really big number and watching the memory of the program as it runs (say, through top):

    foreach (0..100_000_000) { $i++ }

    Compare this with the memory usage of something like the following. Notice I had to drop the number from 100 million to just one million; 100 million caused perl to die with an out of memory error.

    @array = (0..1_000_000); foreach (@array) { $i++ }

    This optimization was added to perl 5.005; perldoc perl5005delta mentions it, search for 1000000.