Created
September 19, 2012 20:08
-
-
Save waffle2k/3751928 to your computer and use it in GitHub Desktop.
Example of caching a result within a file to be pulled later
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use strict; | |
use Attribute::Handlers; | |
my $cachettl = 30; | |
sub write_to_cache { | |
my ($v) = @_; | |
open CACHE, '>/tmp/cache'; | |
use Data::Dumper; | |
$Data::Dumper::Terse=1; | |
print CACHE Dumper( $v ); | |
close CACHE; | |
} | |
sub read_from_cache { | |
# Check the staleness of a file | |
my @stat = stat '/tmp/cache'; | |
return undef if time - $stat[9] > $cachettl; # 30 second cache | |
open CACHE, '</tmp/cache' || return undef; | |
my $str = do { local $/; <CACHE>; }; | |
close CACHE; | |
my $v = eval ( $str ); | |
return $v; | |
} | |
sub UNIVERSAL::cache : ATTR(CODE) { | |
my ( $pkg, $sym, $code ) = @_; | |
no warnings 'redefine'; | |
*{$sym} = sub { | |
my $v = read_from_cache(); | |
unless( $v ){ | |
my $r = $code->(@_); | |
write_to_cache $r; | |
return $r; | |
} | |
return $v; | |
}; | |
} | |
sub foo : cache { | |
return scalar gmtime; | |
} | |
print "Getting the time... ", foo(), "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment