[prog] quick perl question

Jacinta Richardson jarich at perltraining.com.au
Fri Mar 5 05:54:10 EST 2004


On Thu, 4 Mar 2004, Caroline Johnston wrote:

> Many thanks. 
> 
> Is it ok to declare a variable in a loop? Does it get binned at the end 
> and recreated at the start of every loop? Does it matter if it does?

Goodness, that was quick.  Yes, it's more than ok to declare a variable in
a loop.  It's preferable to give your variables the smallest scope you can
for them to fulfil their purpose.  A variable declared with "my" exists
from where it's declared to the end of it's block.  The biggest block is
the whole file, then after that block is any code within the same set of
curlies.

When a variable is declared in a loop it exists only inside that loop and
is binned and recreated each time through the loop.  This is considered a
good thing.

YOu can learn more about scope and lexical variables (those declared with
"my") in our Introduction to Perl course.  I can see you already have a
pretty good grasp on Perl but it shouldn't take you more than a couple of
hours to read over the notes.  The course notes can be found at: 
http://www.perltraining.com.au/notes.html

All the best,

            Jacinta

--
   ("`-''-/").___..--''"`-._          |  Jacinta Richardson         |
    `6_ 6  )   `-.  (     ).`-.__.`)  |  Perl Training Australia    |
    (_Y_.)'  ._   )  `._ `. ``-..-'   |      +613 9354 6001         |  
  _..`--'_..-_/  /--'_.' ,'           | contact at perltraining.com.au |
(il),-''  (li),'  ((!.-'              |   www.perltraining.com.au   |



More information about the Programming mailing list