in reply to Re: where to declare a variable...
in thread where to declare a variable...

In this example, $item ... wasn't going to used outside of the loop, it should have been declared inside of the loop so that it was destroyed (and the memory it uses freed) when the block exits.

You raise a valid point, but perhaps chose an inappropriate example. Particularly when a block is the body of a loop, you should weight the cost of creating and destroying a loop-scoped lexical variable against the need to keep the memory from being tied up. In this particular (obviously contrived) example, I might leave $item scoped outside the loop if I knew the loop would execute many times, just to avoid the create/destroy cost in terms of execution time and memory fragmentation (which itself might cost execution time later in the program, by slowing down subsequent allocations).

dmm


You can give a man a fish and feed him for a day ...
Or, you can teach him to fish and feed him for a lifetime

Replies are listed 'Best First'.
Re: Re(2): where to declare a variable...
by Ven'Tatsu (Deacon) on Dec 10, 2001 at 00:54 UTC
    In perl the lexical creation of my is a compile time action, The only run time effect is that it is asigned to or set to undef. local on the other hand is a run time directive and will have a speed penalty.
    There is still a cost of entering and leaving lexical scopes in perl, but it is incured reguardless of variable declarations.