Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Use of "my" after Perl v5.14

by Rohit Jain (Sexton)
on Sep 20, 2012 at 23:09 UTC ( #994776=note: print w/ replies, xml ) Need Help??


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: -

use 5.010; sub marine { state $n = 0; # private, persistent variable $n $n += 1; print "Hello, sailor number $n!\n"; }
Had the declaration been "my $n = 0", then for every subroutine call it would start with 0.. Thanks everyone for your reply.. :)


Comment on Re: Use of "my" after Perl v5.14
Download Code
Re^2: Use of "my" after Perl v5.14
by chromatic (Archbishop) on Sep 20, 2012 at 23:33 UTC

    Almost exactly right! A state variable has a lexical scope of visibility, but the value persists across control flow leaving that scope.

Re^2: Use of "my" after Perl v5.14
by 2teez (Priest) on Sep 21, 2012 at 02:21 UTC

    Had the declaration been "my $n = 0", then for every subroutine call it would start with 0...

    Depending on where "my $n = 0" was placed and how.
    Using "my $n = 0" outside the subrourtine, placed in a block like so:

    for (1..5){marine()}; { my $n=0; # private, persistent variable $n sub marine { $n += 1; print "Hello, sailor number $n!\n"; } }
    will work exactly, like using:
    use 5.010; for (1..5){marine()}; sub marine { state $n = 0; # private, persistent variable $n $n += 1; print "Hello, sailor number $n!\n"; }

    If you tell me, I'll forget.
    If you show me, I'll remember.
    if you involve me, I'll understand.
    --- Author unknown to me

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://994776]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (13)
As of 2014-09-30 14:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (375 votes), past polls