in reply to Re^3: Using Array of Arrays
in thread Using Array of Arrays

Ah, you are too wise, GrandFather. I'll convert from my COBOL thinking of 'Knowing where to look when my memory fails' to the perl way of 'it's right there in front of you'. However, what if I declare a field within a foreach loop, can I then use it after the loop exits? Thanks.

Replies are listed 'Best First'.
Re^5: Using Array of Arrays
by GrandFather (Saint) on Sep 21, 2007 at 21:30 UTC

    The key is "as late as possible". If you need to retain a value determined in a loop then the variable has to be declared outside the loop:

    my $result; for my $loopVar (...) { ... $result = ...; ... } if (defined $result) { # use the result } else { # result not determined (or undef) }

    Note that $loopVar is magical. It gets aliased to each value in the list that the loop iterates over. In particular It does not retain the value from the last iteration of the loop even if declared outside the loop! Always either use the default variable($_) or explicitly declare the loop variable as shown in the code sample.


    Perl is environmentally friendly - it saves trees
      So if I declare a field outside of a loop (as in the my $result above), I can modify it inside the loop, and still have access to it outside, when the loop is done, but, I can't depend on the actual LOOP variable ($loopVar)to be set to any specific value, anywhere but INside the loop, correct? Thanks for your help and patience, Grandfather, this is getting more fun by the minute.