This is Bavaria, Germany!
When getting information is expensive you would like to cache them. But only for a fixed time, after that time the information shall expire. The modules from Cache::Cache in Perl help.
Cache::Cache does not cache files! It caches a data-structure, for example a hash.
#!/usr/bin/perl
use strict;
use warnings;
use Cache::FileCache;
use Log::Log4perl qw/:easy/;
# initialize Logger
Log::Log4perl->easy_init($INFO);
my $logger = get_logger;
# You do not _need_ any of these options
my $cache_options_ref = {
# there can be several namespace in parallel
namespace => 'my_customerinfo',
default_expires_in => '10 seconds',
auto_purge_interval => '1 hour',
# Arguments only for Cache::FileCache
# where do the cache-files live? Should be a dedicated directory.
# Directory will be created (including complete path) if it doesn't exist
cache_root => './my_cache',
};
my $cache = Cache::FileCache->new($cache_options_ref);
my ( $wanted_name, $action ) = @ARGV;
&usage unless $wanted_name;
$logger->info("Wanted customer ist $wanted_name");
if ( defined $action && $action eq "delete" ) {
# Cachedata shall be deleted
$logger->info("Remove cache for customer $wanted_name");
$cache->remove($wanted_name);
}
# Try to get customers data from cache
my $customer = $cache->get($wanted_name);
if ( not defined $customer ) {
$logger->info("Could not find customer in my cache");
my $customer_data = &get_customer_data($wanted_name);
# Set got data into the cache
$cache->set( $wanted_name, $customer_data );
$customer = $cache->get($wanted_name);
}
$logger->info("Hit! I found customer $wanted_name in my cache");
$logger->info(
sprintf( "%s lives in %s", $customer->{fullname}, $customer->{city} ) );
=head2 get_customer_data
Get customer's data from an expensive, slow source.
Return a hash with data.
=cut
sub get_customer_data {
my $customer_name = shift;
$logger->info("Get $customer_name customer's data from slow source.");
my $customer_data = {
fullname => sprintf( "%s Coorp.", uc($customer_name) ),
city => sprintf( "City of %s", ucfirst($customer_name) ),
};
return $customer_data;
}
sub usage {
die "Usage: $0 customername";
}