Slash Boxes
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

jozef (8299)

  (email not shown publicly)

Journal of jozef (8299)

Friday August 28, 2009
11:05 AM

use feature 'state'; # for caching

[ #39546 ]

What about using the fact that the state declared variable will never be reinitialize for caching? Let's say the path, filename and filecontent will never change no matter how many calls are made to the function where it is needed. Then:

state $filename = File::Spec->catfile('path', 'path', 'filename.txt');

will cache the File::Spec call. Unfortunately this doesn't work:

state @content = read_file($filename);
# => Initialization of state variables in list context currently forbidden

In this case the working "cached versions" is more verbose:

state @content; @content = read_file($filename) if not @content;

The only problem of this persistent state is that it is persistent :) so memory of the variable will be freed only at the end of program. (or if undef is assigned, but then the reinitialization doesn't work and there is probably a better way how to do caching then with state) Should be OK for short running scripts.

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
More | Login | Reply
Loading... please wait.