| 1 | # Copyright 2008, 2009, 2010 Kevin Ryde | ||
| 2 | |||
| 3 | # This file is part of Chart. | ||
| 4 | # | ||
| 5 | # Chart is free software; you can redistribute it and/or modify it under the | ||
| 6 | # terms of the GNU General Public License as published by the Free Software | ||
| 7 | # Foundation; either version 3, or (at your option) any later version. | ||
| 8 | # | ||
| 9 | # Chart is distributed in the hope that it will be useful, but WITHOUT ANY | ||
| 10 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS | ||
| 11 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more | ||
| 12 | # details. | ||
| 13 | # | ||
| 14 | # You should have received a copy of the GNU General Public License along | ||
| 15 | # with Chart. If not, see <http://www.gnu.org/licenses/>. | ||
| 16 | |||
| 17 | package App::Chart::Memoize::ConstSecond; | ||
| 18 | use 5.006; | ||
| 19 | ## no critic (RequireUseStrict RequireUseWarnings) | ||
| 20 | no warnings; | ||
| 21 | |||
| 22 | sub import { | ||
| 23 | my @names = @_; | ||
| 24 | my $package = caller; | ||
| 25 | foreach my $name (@names) { | ||
| 26 | if ($name !~ /::/) { | ||
| 27 | $name = "${package}::$name"; | ||
| 28 | } | ||
| 29 | my $old = \&$name; | ||
| 30 | my $last_time = time() - 1; | ||
| 31 | my $last_value; | ||
| 32 | *$name = sub { | ||
| 33 | my $t = time(); | ||
| 34 | if ($t == $last_time) { | ||
| 35 | return $last_value; | ||
| 36 | } else { | ||
| 37 | $last_time = $t; | ||
| 38 | return ($last_value = $old->(@_)); | ||
| 39 | } | ||
| 40 | }; | ||
| 41 | } | ||
| 42 | } | ||
| 43 | |||
| 44 | 1; | ||
| 45 | __END__ |