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

Re^5: 'state' variables and unit testing (intentional)

by Jenda (Abbot)
on Feb 02, 2014 at 12:10 UTC ( #1073046=note: print w/replies, xml ) Need Help??


in reply to Re^4: 'state' variables and unit testing (intentional)
in thread 'state' variables and unit testing

Unlike the solution using state the my in an enclosing block allows you to include controlled access to the cache.

{ my $_cache; sub withLongComputation { $_cache //= ...; ... } sub clearCache { undef $_cache; } }

Jenda
Enoch was right!
Enjoy the last years of Rome.

Replies are listed 'Best First'.
Re^6: 'state' variables and unit testing (intentional)
by tobyink (Abbot) on Feb 04, 2014 at 13:08 UTC

    An an alternative:

    { use Scope::Guard; my $_cache; sub withLongComputation { $_cache //= ...; ...; } sub localClearCache { my $old = $_cache; undef $_cache; return guard { $_cache = $old }; } } ...; withLongComputation(); withLongComputation(); { my $guard = localClearCache(); # here, $_cache has been cleared withLongComputation(); } # Because $guard has fallen out of scope, # $_cache has been restored to its old value withLongComputation();
    use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1073046]
help
Chatterbox?
[marioroy]: Wow. It's cool seeing Github coments "Update Monster.pm, Create Wild_hairs, Create alternate- PurpleOnGreen..., Then a location, Create Aleenia. Amazing, really. Thank you for sharing.
Discipulus when naming is clear and you know how to arrange the data, then coding it is a mere writing work
[Lady_Aleena]: marioroy, welcome to my insanity. 8)
marioroy likes Dragod, an unbelievably huge dragon. It is bigger than any planet. Wow.
[Lady_Aleena]: marioroy, not my creation, it was submitted a long long time ago when I had submission forms with a form script I can't remember the name of off the top of my head.

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (9)
As of 2017-05-29 09:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?