in reply to where to declare a variable...

Dvergin is indeed correct when he says that you should declare @entries right before the if blocks; assuming, that is, that you are going to be using it outside of the if blocks. However, if the usage is going to be exclusive to inside of the blocks, you may want to consider declaring it twice, once for each block. Garbage collection is done at the end of the block the variable is declared in, so you will want your variables garbage collected as soon as possible if you are no longer using it. Here is an example:

my $entry = 1; my $item; while($entry) { $item = "foobar"; print $item; $entry--; }

In this example, $item is declared out of the loop, even though it is not used outside of the loop. Since it 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.

From looking at the context of your code, it appears that you might want to use @entries outside of the if statements, so you should follow dvergin's suggestion. Otherwise, always make sure that you declare your variables in the inner-most possible block that you can so that you don't unnecessarily tie up memory

Replies are listed 'Best First'.
Re(2): where to declare a variable...
by dmmiller2k (Chaplain) on Dec 09, 2001 at 23:21 UTC
    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
    
      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.