in reply to Understanding difference between my and local variables.
Short version:
local doesn't declare variables. It saves the value of a package variable and makes it so the value gets restored when the lexical scope is exited.
1) Can global variable be declared anywhere in the code or only at the beginning of the code ?
Lexical variables can be declared anywhere an expression can be found.
Package variables need not be declared. use vars can be present anywhere a statement can be found.
our, which creates a lexical alias to a package var, can be present anywhere an expression can be found.
2) If local variable and my variable both are declared using same name, is that allowed or is that an error ?
local doesn't declare variables. It saves the value of a package variable and makes it so the value gets restored when the lexical scope is exited.
In our vs my, the latter wins IIRC. Easy to test.
4) If a sub() is declared within a sub(), can the variables declared in super sub() be accessed in child sub() without being declared in child () ?
If the inner sub is an anonymous sub, yes. Even if the outer sub has exited before the inner sub has exited.
>perl -E"sub mk { my $x=$_[0]; sub { $x } } $x=mk('a'); $y=mk('b'); s +ay $x->(),$y->()" ab
Don't nest named subs. You'll likely end up with buggy code (a warning will be issued if you have them on and the buggy situation arises), and it doesn't serve any purpose (the inner sub isn't public).
5) Declaring variables at the beginning of the code using "use vars", is it the only way to declare global variables ?
use vars and our.
or just declaring variables in the beginning of the code without local or my makes them global variables ?
Global variables are created on the fly whenever they are used.
6) what is the difference between my $b; and my ($b);
The latter is considered a list in order to determine if an assignment operator is a scalar assignment operator or a list assignment operator.
# The "=" is a scalar assignment operator, so: # - f() is evaluated in scalar context. # - The assignment returns $x. my $x = f(); # The "=" is a list assignment operator, so: # - f() is evaluated in list context. # - The assignment returns ($x) in list context, or # - the number of items returned by f() in scalar context. my ($x) = f();
7) If my variable is declared to make its scope local
local doesn't declare variables. local doesn't change the scope of a variable.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Understanding difference between my and local variables.
by ig (Vicar) on Oct 15, 2010 at 05:42 UTC | |
by ikegami (Patriarch) on Oct 15, 2010 at 08:07 UTC | |
|
Re^2: Understanding difference between my and local variables.
by manishrathi (Beadle) on Oct 15, 2010 at 05:41 UTC | |
by JavaFan (Canon) on Oct 15, 2010 at 05:57 UTC | |
by ikegami (Patriarch) on Oct 15, 2010 at 07:12 UTC |