The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.


Redis - Perl binding for Redis database


version 1.961


    ## Defaults to $ENV{REDIS_SERVER} or
    my $redis = Redis->new;

    my $redis = Redis->new(server => '');

    ## Set the connection name (requires Redis 2.6.9)
    my $redis = Redis->new(server => '', name => 'my_connection_name');

    ## Use UNIX domain socket
    my $redis = Redis->new(sock => '/path/to/socket');

    ## Enable auto-reconnect
    ## Try to reconnect every 500ms up to 60 seconds until success
    ## Die if you can't after that
    my $redis = Redis->new(reconnect => 60);

    ## Try each 100ms upto 2 seconds (every is in milisecs)
    my $redis = Redis->new(reconnect => 2, every => 100);

    ## Disable the automatic utf8 encoding => much more performance
    ## !!!! This will be the default after 2.000, see ENCODING below
    my $redis = Redis->new(encoding => undef);

    ## Use all the regular Redis commands, they all accept a list of
    ## arguments
    ## See for full list
    $redis->set('key' => 'value');
    $redis->sort('list', 'DESC');
    $redis->sort(qw{list LIMIT 0 5 ALPHA DESC});

    ## Add a coderef argument to run a command in the background
    $redis->sort(qw{list LIMIT 0 5 ALPHA DESC}, sub {
      my ($reply, $error) = @_;
      die "Oops, got an error: $error\n" if defined $error;
      print "$_\n" for @$reply;
    ## or

    ## Or run a large batch of commands in a pipeline
    my %hash = _get_large_batch_of_commands();
    $redis->hset('h', $_, $hash{$_}, sub {}) for keys %hash;

    ## Publish/Subscribe
      sub {
        my ($message, $topic, $subscribed_topic) = @_

          ## $subscribed_topic can be different from topic if
          ## you use psubscribe() with wildcards
    $redis->psubscribe('nasdaq.*', sub {...});

    ## Blocks and waits for messages, calls subscribe() callbacks
    ##  ... forever
    my $timeout = 10;
    $redis->wait_for_messages($timeout) while 1;

    ##  ... until some condition
    my $keep_going = 1; ## other code will set to false to quit
    $redis->wait_for_messages($timeout) while $keep_going;

    $redis->publish('topic_1', 'message');


Pure perl bindings for

This version supports protocol 2.x (multi-bulk) or later of Redis available at

This documentation lists commands which are exercised in test suite, but additional commands will work correctly since protocol specifies enough information to support almost all commands with same piece of code with a little help of AUTOLOAD.


Usually, running a command will wait for a response. However, if you're doing large numbers of requests, it can be more efficient to use what Redis calls pipelining: send multiple commands to Redis without waiting for a response, then wait for the responses that come in.

To use pipelining, add a coderef argument as the last argument to a command method call:

  $r->set('foo', 'bar', sub {});

Pending responses to pipelined commands are processed in a single batch, as soon as at least one of the following conditions holds:

  • A non-pipelined (synchronous) command is called on the same connection

  • A pub/sub subscription command (one of subscribe, unsubscribe, psubscribe, or punsubscribe) is about to be called on the same connection.

  • One of "wait_all_responses" or "wait_one_response" methods is called explicitly.

The coderef you supply to a pipelined command method is invoked once the response is available. It takes two arguments, $reply and $error. If $error is defined, it contains the text of an error reply sent by the Redis server. Otherwise, $reply is the non-error reply. For almost all commands, that means it's undef, or a defined but non-reference scalar, or an array ref of any of those; but see "keys", "info", and "exec".

Note the contrast with synchronous commands, which throw an exception on receipt of an error reply, or return a non-error reply directly.

The fact that pipelined commands never throw an exception can be particularly useful for Redis transactions; see "exec".


This feature is deprecated and will be removed before 2.000. You should start testing your code with encoding => undef because that will be the new default with 2.000.

Since Redis knows nothing about encoding, we are forcing utf-8 flag on all data received from Redis. This change was introduced in 1.2001 version. Please note that this encoding option severely degrades performance.

You can disable this automatic encoding by passing an option to "new": encoding => undef.

This allows us to round-trip utf-8 encoded characters correctly, but might be problem if you push binary junk into Redis and expect to get it back without utf-8 flag turned on.




    my $r = Redis->new; # $ENV{REDIS_SERVER} or

    my $r = Redis->new( server => '', debug => 0 );
    my $r = Redis->new( server => '', encoding => undef );
    my $r = Redis->new( sock => '/path/to/sock' );
    my $r = Redis->new( reconnect => 60, every => 5000 );
    my $r = Redis->new( password => 'boo' );
    my $r = Redis->new( on_connect => sub { my ($redis) = @_; ... } );
    my $r = Redis->new( name => 'my_connection_name' ); ## Redis 2.6.9 required

The server parameter specifies the Redis server we should connect to, via TCP. Use the 'IP:PORT' format. If no server option is present, we will attempt to use the REDIS_SERVER environment variable. If neither of those options are present, it defaults to ''.

Alternatively you can use the sock parameter to specify the path of the UNIX domain socket where the Redis server is listening.

The REDIS_SERVER can be used for UNIX domain sockets too. The following formats are supported:

  • /path/to/sock

  • unix:/path/to/sock


  • tcp:

The encoding parameter speficies the encoding we will use to decode all the data we receive and encode all the data sent to the redis server. Due to backwards-compatibility we default to utf8. To disable all this encoding/decoding, you must use encoding => undef. This is the recommended option.

Warning: this option has several problems and it is deprecated. A future version might add other filtering options though.

The reconnect option enables auto-reconnection mode. If we cannot connect to the Redis server, or if a network write fails, we enter retry mode. We will try a new connection every every miliseconds (1000ms by default), up-to reconnect seconds.

Be aware that read errors will always thrown an exception, and will not trigger a retry until the new command is sent.

If we cannot re-establish a connection after reconnect seconds, an exception will be thrown.

If your Redis server requires authentication, you can use the password attribute. After each established connection (at the start or when reconnecting), the Redis AUTH command will be send to the server. If the password is wrong, an exception will be thrown and reconnect will be disabled.

You can also provide a code reference that will be immediatly after each sucessfull connection. The on_connect attribute is used to provide the code reference, and it will be called with the first parameter being the Redis object.

You can also set a name for each connection. This can be very useful for debugging purposes, using the CLIENT LIST command. To set a connection name, use the name parameter. Please note that there are restrictions on the name you can set, the most important of which is, no spaces. See the CLIENT SETNAME documentation for all the juicy details. This feature is safe to use with all versions of Redis servers. If CLIENT SETNAME support is not available (Redis servers 2.6.9 and above only), the name parameter is ignored.

The debug parameter enables debug information to STDERR, including all interactions with the server. You can also enable debug with the REDIS_DEBUG environment variable.

Connection Handling



Closes the connection to the server. The quit method does not support pipelined operation.


  $r->ping || die "no server?";

The ping method does not support pipelined operation.


  @clients = $r->client_list;

Returns list of clients connected to the server. See CLIENT LIST documentation for a description of the fields and their meaning.


  my $connection_name = $r->client_getname;

Returns the name associated with this connection. See "client_setname" or the name parameter to "new" for ways to set this name.



Sets this connection name. See the CLIENT SETNAME documentation for restrictions on the connection name string. The most important one: no spaces.

Pipeline management


Waits until all pending pipelined responses have been received, and invokes the pipeline callback for each one. See "PIPELINING".


Waits until the first pending pipelined response has been received, and invokes its callback. See "PIPELINING".

Transaction-handling commands

Warning: the behaviour of these commands when combined with pipelining is still under discussion, and you should NOT use them at the same time just now.

You can follow the discussion to see the open issues with this.






  my @individual_replies = $r->exec;

exec has special behaviour when run in a pipeline: the $reply argument to the pipeline callback is an array ref whose elements are themselves [$reply, $error] pairs. This means that you can accurately detect errors yielded by any command in the transaction, and without any exceptions being thrown.

Commands operating on string values


  $r->set( foo => 'bar' );

  $r->setnx( foo => 42 );


  my $value = $r->get( 'foo' );


  my @values = $r->mget( 'foo', 'bar', 'baz' );



  $r->incrby('tripplets', 3);



  $r->decrby('tripplets', 3);


  $r->exists( 'key' ) && print "got key!";


  $r->del( 'key' ) || warn "key doesn't exist";


  $r->type( 'key' ); # = string

Commands operating on the key space


  my @keys = $r->keys( '*glob_pattern*' );
  my $keys = $r->keys( '*glob_pattern*' ); # count of matching keys

Note that synchronous keys calls in a scalar context return the number of matching keys (not an array ref of matching keys as you might expect). This does not apply in pipelined mode: assuming the server returns a list of keys, as expected, it is always passed to the pipeline callback as an array ref.


  my $key = $r->randomkey;


  my $ok = $r->rename( 'old-key', 'new-key', $new );


  my $nr_keys = $r->dbsize;

Commands operating on lists

See also Redis::List for tie interface.


  $r->rpush( $key, $value );


  $r->lpush( $key, $value );


  $r->llen( $key );


  my @list = $r->lrange( $key, $start, $end );


  my $ok = $r->ltrim( $key, $start, $end );


  $r->lindex( $key, $index );


  $r->lset( $key, $index, $value );


  my $modified_count = $r->lrem( $key, $count, $value );


  my $value = $r->lpop( $key );


  my $value = $r->rpop( $key );

Commands operating on sets


  my $ok = $r->sadd( $key, $member );


  my $n_elements = $r->scard( $key );


  my @elements = $r->sdiff( $key1, $key2, ... );
  my $elements = $r->sdiff( $key1, $key2, ... ); # ARRAY ref


  my $ok = $r->sdiffstore( $dstkey, $key1, $key2, ... );


  my @elements = $r->sinter( $key1, $key2, ... );
  my $elements = $r->sinter( $key1, $key2, ... ); # ARRAY ref


  my $ok = $r->sinterstore( $dstkey, $key1, $key2, ... );


  my $bool = $r->sismember( $key, $member );


  my @elements = $r->smembers( $key );
  my $elements = $r->smembers( $key ); # ARRAY ref


  my $ok = $r->smove( $srckey, $dstkey, $element );


  my $element = $r->spop( $key );


  my $element = $r->srandmember( $key );


  $r->srem( $key, $member );


  my @elements = $r->sunion( $key1, $key2, ... );
  my $elements = $r->sunion( $key1, $key2, ... ); # ARRAY ref


  my $ok = $r->sunionstore( $dstkey, $key1, $key2, ... );



  $r->sort("key BY pattern LIMIT start end GET pattern ASC|DESC ALPHA');

Publish/Subscribe commands

When one of "subscribe" or "psubscribe" is used, the Redis object will enter PubSub mode. When in PubSub mode only commands in this section, plus "quit", will be accepted.

If you plan on using PubSub and other Redis functions, you should use two Redis objects, one dedicated to PubSub and the other for regular commands.

All Pub/Sub commands receive a callback as the last parameter. This callback receives three arguments:

  • The published message.

  • The topic over which the message was sent.

  • The subscribed topic that matched the topic for the message. With "subscribe" these last two are the same, always. But with "psubscribe", this parameter tells you the pattern that matched.

See the Pub/Sub notes for more information about the messages you will receive on your callbacks after each "subscribe", "unsubscribe", "psubscribe" and "punsubscribe".


  $r->publish($topic, $message);

Publishes the $message to the $topic.


      sub {
        my ($message, $topic, $subscribed_topic) = @_;

Subscribe one or more topics. Messages published into one of them will be received by Redis, and the specificed callback will be executed.


  $r->unsubscribe(@topic_list, sub { my ($m, $t, $s) = @_; ... });

Stops receiving messages for all the topics in @topic_list.


  my @topic_matches = ('prefix1.*', 'prefix2.*');
  $r->psubscribe(@topic_matches, sub { my ($m, $t, $s) = @_; ... });

Subscribes a pattern of topics. All messages to topics that match the pattern will be delivered to the callback.


  my @topic_matches = ('prefix1.*', 'prefix2.*');
  $r->punsubscribe(@topic_matches, sub { my ($m, $t, $s) = @_; ... });

Stops receiving messages for all the topics pattern matches in @topic_list.


  if ($r->is_subscriber) { say "We are in Pub/Sub mode!" }

Returns true if we are in Pub/Sub mode.


  my $keep_going = 1; ## Set to false somewhere to leave the loop
  my $timeout = 5;
  $r->wait_for_messages($timeout) while $keep_going;

Blocks, waits for incoming messages and delivers them to the appropriate callbacks.

Requires a single parameter, the number of seconds to wait for messages. Use 0 to wait for ever. If a positive non-zero value is used, it will return after that ammount of seconds without a single notification.

Please note that the timeout is not a commitement to return control to the caller at most each timeout seconds, but more a idle timeout, were control will return to the caller if Redis is idle (as in no messages were received during the timeout period) for more than timeout seconds.

The "wait_for_messages" call returns the number of messages processed during the run.

Persistence control commands







Scripting commands


  $r->eval($lua_script, $num_keys, $key1, ..., $arg1, $arg2);

Executes a Lua script server side.

Note that this commands sends the Lua script every time you call it. See "evalsha" and "script_load" for an alternative.


  $r->eval($lua_script_sha1, $num_keys, $key1, ..., $arg1, $arg2);

Executes a Lua script cached on the server side by its SHA1 digest.

See "script_load".


  my ($sha1) = $r->script_load($lua_script);

Cache Lua script, returns SHA1 digest that can be used with "evalsha".


  my ($exists1, $exists2, ...) = $r->script_exists($scrip1_sha, $script2_sha, ...);

Given a list of SHA1 digests, returns a list of booleans, one for each SHA1, that report the existence of each script in the server cache.



Kills the currently running script.



Flush the Lua scripts cache.

Remote server control commands


  my $info_hash = $r->info;

The info method is unique in that it decodes the server's response into a hashref, if possible. This decoding happens in both synchronous and pipelined modes.



The shutdown method does not support pipelined operation.

Multiple databases handling commands


  $r->select( $dbindex ); # 0 for new clients


  $r->move( $key, $dbindex );







You can find documentation for this module with the perldoc command.

  perldoc Redis


The following websites have more information about this module, and may be of help to you. As always, in addition to those websites please use your favorite search engine to discover more resources.


You can email the author of this module at MELO at asking for help with any problems you have.

Bugs / Feature Requests

Please report any bugs or feature requests through the web interface at You will be automatically notified of any progress on the request by the system.

Source Code

The code is open to the world, and available for you to hack on. Please feel free to browse it and play with it, or whatever. If you want to contribute patches, please send me a diff or prod me to pull from your repository :)

  git clone git://


The following persons contributed to this project (alphabetical order):

  • Aaron Crane (pipelining and AUTOLOAD caching support)

  • Dirk Vleugels

  • Flavio Poletti

  • Jeremy Zawodny

  • sunnavy at

  • Thiago Berlitz Rondon

  • Ulrich Habel


Pedro Melo <>


This software is Copyright (c) 2012 by Pedro Melo.

This is free software, licensed under:

  The Artistic License 2.0 (GPL Compatible)