use strict; use warnings; $undeclaredVar = 0; # strict gets grumpy about this because the variable isn't declared my $globalVar = 0; # This variable can be used by any following part of the code for my $loopVar (1 .. 10) { # In the scope of the for loop. $loopVar can only be used within this loop # Loop variables are somewhat magical my $localVar = $loopVar * 3; # This variable is also local to the loop. It # is a different variable each time through the loop! my $globalVar = $localVar; # Bad! This $globalVar hides the $globalVar # declared outside the loop. Reusing variable names like this is very # bad style! if ($localVar == 9) { my $nestedVar = rand(10); # This variable is only available inside this # if block. It's not available in the else part or after the if } else { my $nestedVar = rand($localVar); # Reusing the name here is ok, but note # that this is a different variable than the $nestedVar in the if # block. Note that we can use variables from the encompassing # scope in a nested scope. } my @trailingVar; # This array variable isn't available to any earlier part # of the program. In general declare variables in as small a scope as # you can and initialize them to the first value they should have. # Arrays and hashes are created empty so they don't generally need an # explicit initial value. } my @anotherGlobal = ('Hello', 'World'); # This global array variable isn't # available to the loop code above because it's declared after the loop. # Note that we can initialize an array variable using a list