Always declare variables in the smallest scope you can. There is a nasty trap implied by your code. Consider:
use strict;
use warnings;
my $var = 'wibble';
foreach $var qw(foo bar) {
print "$var\n";
}
print $var;
Prints:
foo
bar
wibble
Did you expect 'wibble' or 'bar' for that last value?
The $var you declared outside the loop is not the $var used inside the loop. The loop variable is aliased to each value the loop iterates over. Using the form for my $var makes it clear to everyone that the scope of $var is just the loop and avoids the unfortunate assumption that the last value "assigned" to $var is available after the loop. Not a problem for your sample code, but a nasty trap waiting to bite you one day.
DWIM is Perl's answer to Gödel
|