All,
For C programmer's, declaring variables in Perl6 with state won't seem very foreign - just think static. In a nutshell, declaring a variable with state only initializes the variable once and any time the sub is re-invoked the variable retains its previous value. Update: This is inaccurate - read the authorative explanation.
The cache variable doesn't necessarily need to be used to calculate the return value of the sub which would be made easy using Memoize.
Here is an example I, and others, wrote before Pugs had OO.
#!/usr/bin/pugs # Demo of the state() variable declaration. # This is also a neat way of doing OO without actually having OO avail +able. use v6; sub gen_cashier () { # This variable corresponds to a class variable. # It is shared across all "instances" of gen_cashier(). state $cash_in_store = 0; # One could add my() variables here, which correspond to instance +variables. # These would not be shared. # Finally, we return a hashref which maps method names to code. return { add => { $cash_in_store += $^amount }, del => { $cash_in_store -= $^amount }, bal => { $cash_in_store }, }; } my $drawer; $drawer[$_] = gen_cashier() for 1..3; $drawer[1]<add>( 59 ); $drawer[2]<del>( 17 ); say $drawer[3]<bal>(); # This should say "42"
The place I think it would come in most handy is for caching*. In p5, if a cache variable (%seen for instance) is supposed to belong to a sub that needs to persist across invocations, you need to do things like:
- Pass the cache variable as an argument
- Scope the variable at the package level
- Use naked blocks to create a closure
sub foo () { state %seen; # ... }
So how will you use state declared variables in Perl6?
Cheers - L~R
Back to
Meditations