use feature 'state'; # for caching

jozef on 2009-08-28T16:05:20

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.