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

There is a piece of common wisdom that says that you can remember about seven things at a time in your short term memory (Human register set I guess). So, given that limitation there is no reason at all to declare all your variables in one place at the start of anything - you'll forget them anyway.

However, the much more important reason for declaring a variable as late as possible is that it is much easier to see where and how it is used. There is no need to know about a variable until the variable is needed so there is no need to burden the limited storage facility of the reader of your code by introducing variables before they are needed. Bottom line: Declaring variables early doesn't help anyone.

There is nothing wrong with learning about the 'raw "under the covers" way to do it', but there are some tasks such as parsing generally, and parsing markup in particular that are much more subtle than one might first think. It is well worth being aware of the modules that are available for performing such tasks after your initial foray into rolling your own.


Perl is environmentally friendly - it saves trees

Replies are listed 'Best First'.
Re^4: Using Array of Arrays
by Aim9b (Monk) on Sep 21, 2007 at 11:19 UTC
    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.

      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.