There is an ongoing outage on the primary CPAN mirror. It is possible to work around the issue by using MetaCPAN as a mirror.

PDK::Utils::Cache - 简单的层级缓存工具类

SYNOPSIS

use PDK::Utils::Cache;

my $cache = PDK::Utils::Cache->new;

# 设置缓存
$cache->set('user', 'profile', 'name', 'Wenwu');
$cache->set('user', 'profile', 'age', 18);

# 获取缓存
my $name = $cache->get('user', 'profile', 'name'); # Wenwu

# 删除指定缓存
$cache->clear('user', 'profile', 'age');

# 清空缓存
$cache->clear();

DESCRIPTION

该模块提供一个基于 Perl 哈希结构的简易缓存工具,支持多级键路径的存取和清除操作,适合在程序运行期间存储临时数据。

ATTRIBUTES

cache

isa => HashRef[Ref]
is  => 'ro'

内部缓存数据结构,默认是一个空的哈希引用。

METHODS

get(@keys)

my $value = $cache->get('user', 'profile', 'name');

根据多级键路径获取缓存值。

等价于调用 locate(@keys)

set(@keys, $value)

$cache->set('user', 'profile', 'name', 'Wenwu');

设置缓存值,支持多级路径。

参数要求:

  • 至少包含一个键和一个值

  • 路径上不存在的键会自动创建为新的哈希引用

  • 如果路径上的某个节点不是哈希引用,会抛出异常

clear(@keys)

$cache->clear();                        # 清除所有缓存
$cache->clear('user', 'profile', 'id'); # 清除指定路径的缓存值

清除缓存数据:

  • 无参数:清空所有缓存

  • 指定路径:删除路径上对应的值

locate(@keys)

my $ref = $cache->locate('user', 'profile');

返回指定路径对应的值或引用。

如果路径不存在,返回 undef。

EXAMPLES

use PDK::Utils::Cache;

my $cache = PDK::Utils::Cache->new;

# 设置缓存
$cache->set('user', 'profile', 'name', 'Wenwu');
$cache->set('user', 'profile', 'age', 18);

# 获取缓存
my $name = $cache->get('user', 'profile', 'name'); # Wenwu

# 删除指定缓存
$cache->clear('user', 'profile', 'age');

# 清空缓存
$cache->clear();

ERROR HANDLING

  • 调用 set 时,如果路径上的某个节点不是哈希引用,会抛出异常。

  • 调用 set 时,如果参数少于两个(缺少键或值),会抛出异常。

AUTHOR

WENWU YAN <968828@gmail.com>

LICENSE AND COPYRIGHT

This software is licensed under the same terms as Perl itself.