Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Bring Out Your New Perl Code

by zby (Vicar)
on Dec 19, 2007 at 09:27 UTC ( [id://657834]=note: print w/replies, xml ) Need Help??


in reply to Bring Out Your New Perl Code

What does the 'state' declaration really do here? How does it make $cash_in_store different from a normal closured variable?

Update: I analyzed it a bit - and I see it now - if $cash_in_store was not declared state then it would not be shared between $drower->[0], $drower->[1], $drower->[2] and $drower->[3]. But of course as a closured variable it still would work for individual drawers.

Replies are listed 'Best First'.
Re^2: Bring Out Your New Perl Code
by grinder (Bishop) on Dec 19, 2007 at 14:15 UTC

    It's the exact difference between the following two code snippets:

    BEGIN { my $var = 10; sub next { return ++$var; } }

    And the following:

    sub next { state $var = 10; return ++$var; }

    Now let's have a show of hands, how many people prefer the First Way To Do It? ... hmm, I see no hands? I thought as much :)

    Tip o' the hat to Roy Johnson for pointing out that it was a BEGIN block I wanted, not an lexical scope with a label BEGIN:. And you do need a BEGIN block, not a bare block, otherwise you can run into grief with uninitialised values (which is kind of the whole point).

    • another intruder with the mooring in the heart of the Perl

      Actually you should compare using a bare block (no BEGIN) which is the standard (older) way to have "state" variables.

      I like 'state' but the old way is still useful if you need a pair of cooperating subs (or more):

      % steph@ape (/home/stephan) % % cat state_old.px #!/usr/bin/perl+ { my $var = 10; sub next1 { ++$var; } sub next1_odd { if ($var % 2 == 0) { ++$var; } else { ++$var; ++$var; } } } $\ = qq{\n}; print next1() for 1..5; print next1_odd(); % steph@ape(/home/stephan) % % perl+ -w state_old.px 11 12 13 14 15 17
      cheers --stephan
Re^2: Bring Out Your New Perl Code
by pfaut (Priest) on Dec 19, 2007 at 11:15 UTC

    It looks like it acts more like a static variable in a C routine. There is no closure in Limbic~Region's code yet the variable looks like it is expected to retain its value between calls.

    90% of every Perl application is already written.
    dragonchild

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2024-04-24 19:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found