in reply to Re^2: newbie learning perl
in thread newbie learning perl
If you don't use "strict" and "my" Perl makes any variables you use "global" (it's a little more subtle that that, but the details aren't important for now). As a general thing global variables are bad news because it's hard to tell where their value might change. "my" declares a variable in the local scope and strict enforces that. strict picks up errors that can be detected at compile time before the program runs.
warnings tell you about dodgy stuff that happens as the program runs, like variables that are used before they have been given a value or using == where eq should be used.
In Perl scope is important. It controls where a lexical variable (one declared with my) can be used. For example:
use strict; use warnings; $undeclaredVar = 0; # strict gets grumpy about this because the variab +le isn't declared my $globalVar = 0; # This variable can be used by any following part o +f the code for my $loopVar (1 .. 10) { # In the scope of the for loop. $loopVar can only be used within t +his 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 $glo +balVar # 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 in +side this # if block. It's not available in the else part or after t +he 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 encompass +ing # scope in a nested scope. } my @trailingVar; # This array variable isn't available to any earl +ier part # of the program. In general declare variables in as small a s +cope as # you can and initialize them to the first value they should h +ave. # Arrays and hashes are created empty so they don't generally +need an # explicit initial value. } my @anotherGlobal = ('Hello', 'World'); # This global array variable i +sn'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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: newbie learning perl
by mkesling (Initiate) on Feb 20, 2015 at 19:03 UTC | |
by GrandFather (Saint) on Feb 20, 2015 at 22:44 UTC | |
by RonW (Parson) on Feb 20, 2015 at 20:58 UTC | |
by mkesling (Initiate) on Feb 20, 2015 at 20:30 UTC |