Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

13.11. Caching with Memoize

If you have a subroutine with simpler logic, where a returned value is solely a function of an input, you can use the Memoize module, which does the caching automatically for you. The gist of its usage is giving the name of the function to be memoize( ) d:

use Memoize;
memoize('slow_function');
slow_function(arguments);

Remember that in our case we had two caches: one for the text versions of the calendars and the other for HTML components. The get_text_calendar( ) function is responsible for populating the text calendar's cache. It depends only on inputs, so we could rewrite it as:

use Memoize;
memoize('get_text_calendar');
sub get_text_calendar {
    my($year,$month) = @_;
    warn "$year,$month\n" if DEBUG;
    my $cal = Date::Calc::Calendar($year, $month);
    chomp $cal;
    return $cal;
}

We have added another debug warning to check that the cache is actually working. If you want to test it under mod_perl, set DEBUG to a true value, start the server in single-process mode (-X), and issue requests to the calendar registry script we just discussed.

You can also control the size of the cache and do other automatic cache manipulations with Memoize. See its manpage for more information.

The get_html_calendar( )subroutine cannot be memoize( ) d because the returned value depends on the relation between the requested date and the current date, in addition to the normal input/output relation.



Copyright © 2003 O'Reilly & Associates. All rights reserved.


 
 
  Published courtesy of O'Reilly Design by Interspire