It seems that with Cache::Memcached::Fast, if you use gets() on a key
that doesn't exist, and use cas() to set the key value later, this
fails, if the key didn't exist at the time you called gets() on it.
The following code succeeds if $keyname is set to a key that already
exists in memcached, however it fails (outputs "Update failed") if
$keyname is set to something that didn't already exist:
****
use Cache::Memcached::Fast;
use strict;
my $keyname = '20090804';
# Configure the memcached server
my $cache = new Cache::Memcached::Fast {
'servers' => [
'localhost:11211',
],
};
print "Existing value: " . $cache->get($keyname) . "\n";
my $cas_val = $cache->gets($keyname);
$$cas_val[1] = 'newval';
if ($cache->cas($keyname, @$cas_val))
{
print "OK, value updated\n";
}
else
{
print "Update failed\n";
}
****
It seems counterintuitive to me that the update would fail if the key
never existed in the first place. My understanding is you use gets
and cas if what you want to do is retrieve a value, and then update
the value only if the value hasn't been changed since you retrieved
it. In the case of a nonexistent key, then the value hasn't
"changed" since you retrieved it (it was empty before, and it still
is), so the update should succeed.
Is there a way to change this behavior? Otherwise, I'll just have to
write code with two branches every time I want to update a value
using gets() and cas() -- first, check if the key already exists (and
if so, update it using gets() and cas()), otherwise, update it using
get() and set() (because I can't get gets() and cas() to work on a
non-pre-existing key).
-Bennett