Apr 6, 2013, 7:53 AM
Post #4 of 7
Limiting the scope of a variable to the chunk of code where it is needed (a block, a subroutine, a package) helps avoiding bugs that are often insidious and difficult to track.
Re: [zolteck06] variable scope
[In reply to]
It also helps maintaining the code. Suppose you have in a long program global variables with very common names such as $line, $file, $count, $size, $sum, @list, etc. You must change the program and have to add a newsubroutine to do something new. If you don't declare locally your variables, you might unexpectedly use a variable name that is used somewhere else in the program and that is likely to break everything, as the $line variable will no longer contain the expected value. If you make your new variables local (or, more precisely lexically scoped) to the new subroutine, then you don't have this danger of side effects: locally in the subroutine, your local variable will contain what you expect, but once you are executing code outside of the subroutine, the variable will contain what the writed of the original code expected it to contain.
Of course, using the 'use strict;' and 'use warnings;' pragmas is part of the same strategy to prevent this type of insidious side effects.