in reply to Use of "my" after Perl v5.14
Ok.. Now that I have read something new, my doubts are clear..
Actually, its not about private or global.. Its about lexical scope of the variable..
when we declare a variable with "my", its lexical scope is the nearest outer block of that variable.. So, a lexical scope can at max be a file..
After Perl 5.10 we can use "state" to define a state variable within subroutine to maintain the state of the variables between different calls.. By this we don't have to use global variables in the subroutine.. And also, we don't have to declare it through "my" which otherwise would have got new value for each call..
E.g: -
Had the declaration been "my $n = 0", then for every subroutine call it would start with 0.. Thanks everyone for your reply.. :)use 5.010; sub marine { state $n = 0; # private, persistent variable $n $n += 1; print "Hello, sailor number $n!\n"; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Use of "my" after Perl v5.14
by 2teez (Vicar) on Sep 21, 2012 at 02:21 UTC | |
|
Re^2: Use of "my" after Perl v5.14
by chromatic (Archbishop) on Sep 20, 2012 at 23:33 UTC |