Keeping things local that should be local is a good housekeeping practice.
Technically speaking, using local (my) variables arises from the need of eliminating namespace clashes, but the fact is it has a somewhat unrelated purpose. That is, to make sure the scope of a variable solely depends on the lexical scope only. So you can tell the scope of the variable directly by looking within the current block and nowhere else. Subroutines invoked from within this block will not see the variable. so,
Code:
{ # BLOCK 1
my $var = 10;
{ # BLOCK 2
local $var2 = 100;
&mysub;
print "\$var = $var\n"; # (1)
print "\$var2 = $var2\n"; # (2)
}
$var += 10;
print "\$var = $var\n"; # (3)
print "\$var2 = $var2\n"; # (4)
}
&mysub;
print "\$var = $var\n"; # (5)
print "\$var2 = $var2\n"; # (6)
sub mysub {
$var += 2;
$var2 += 2;
}
You can tell that the scope of "my $var" is within BLOCK 1 but not to subroutines called inside. So (1) and (3) are 10 and 20 respectively. So which $var did mysub() change in the subroutine? It's the global $var, which is shown in (5) as "4" (2 invocations) after the scope of "my $var" expires. As you can be certain of the scope (instead of depending on the call stack, i.e. the nesting of subroutines that get called), it will be easier to debug when the value goes wrong. Perl also gives you a variant "local" which implements the scope-depend-on-call-stack policy (rare among commonly in-use programming languages today), so (2), (4), (6) are 102, undef and 2. This has a disadvantage that the scope depends on the call stack at runtime so it is more confusing.
If you need to deal with references, you may need to expire a data structure pointed to by a reference at a certain point in the lifetime of the script by controlling the lifetime of the references. If your references are declared as local variables they will naturally go out of scope when the containing block terminates and subsequently get cleaned up. Otherwise, references as global variables will stick around unless you reassign its value. That increases the chance of clashes if you forget to do so.
But bear in mind that Perl global variables are not truly global (see the perlmod manpage), but further subject to the package (a.k.a. namespace) mechanism. Package is the method that addresses name clashes. This is important as we build components that are intended to be reused, so we don't want the $name defined in one component used to clash with another $name in my program. But I'm not going into details of packages here. See the perlmod manpage or relevant literature for details.
This explains why you should try to put your code in modules (at least, in different packages) and use local variables most of the time. Not only this makes your code more reusable, it also helps prevent a lot of problems in the long run as your code becomes more complicated when you try to stick bits and pieces together.