Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

Re: 'my' and 'state' declaration inside a loop

by nemesisgus (Acolyte)
on Aug 05, 2012 at 16:22 UTC ( #985548=note: print w/replies, xml ) Need Help??

in reply to Re: 'my' and 'state' declaration inside a loop
in thread 'my' and 'state' declaration inside a loop

Thank you both for your wisdom.

I read the my and state docs before asking but I couldn't find an answer.

I understand that state was introduced as an improvement to my and that they have different purposes although they are overlapping in some cases and can be used to reach the same effect.

My question was basically conceptual.

Anyway, just if somebody is interested, it seems that there is, of course, a difference:

my $n; for (1..100000000) { $n=0 } real 0m9.395s user 0m9.397s sys 0m0.000s _________________________________ for (1..100000000) { my $n=0 } real 0m12.773s user 0m12.765s sys 0m0.004s _________________________________ for (1..100000000) { state $n=0 } real 0m7.282s user 0m7.244s sys 0m0.008s

Replies are listed 'Best First'.
Re^2: 'my' and 'state' declaration inside a loop
by GrandFather (Sage) on Aug 07, 2012 at 20:32 UTC

    state is not an 'improvement' of my. It is an improvement of Perl to provide a small feature that was missing - scoped static variables. The common part between my and state variables is that they can't be accessed by name outside their lexical scope. The prime difference between them is that my variables get a fresh chunk of memory each time their lexical scope is entered whereas static variables are assigned a chunk of memory at program start time and retain it until execution terminates.

    True laziness is hard work

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://985548]
[LanX]: Free Gelderland!
[erix]: haha
[LanX]: Èrnem rulez!

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (6)
As of 2018-04-24 08:56 GMT
Find Nodes?
    Voting Booth?