Salvador Fandiño García


Hash::Spy - run code when a has is changed


  use Hash::Spy qw(spy_hash);

  my %h = (...)
  spy_hash %h, empty => sub { say "the hash is empty" };

  spy_hash %h, store  => sub { say "hash entry $_[0] => $_[1] is being added" },
               delete => sub { say "hash entry $_[0] is being deleted" },
               clear  => sub { say "the hash is being cleared" };


This module allows to attach to a hash a set of callbacks that will be invoked when it is changed in specific ways.


The following subroutine can be imported from the module:

spy_hash(%hash, %hooks)

The acceptable hooks are as follows:

store => sub { ... }

The given callback is invoked everytime a key/value pair is changed or added to the hash.

The callback arguments are the key and the value.

delete = sub { ... }

The given callback is invoked when some entry is deleted from the hash.

Note that this callback is not invoked when the delete is used for an entry that does not exists on the hash. For instance:

  my %a = (foo => 1, bar => 2);
  spy_hash(%a, delete => sub { say "deleting $_[0]" });
  delete $a{doz}; # the callback is not invoked!
clear => sub { ... }

The given callback is invoked when the hash is non empty and the clear operation is called. That happens when a new set of keys/values is assigned. For instance:

  %a = ();
  %a = (foo => 4, doz => 'juas');
empty => sub { ... }

The given callback is invoked when the last key on the hash is deleted (via delete or clear).

Note that assigning a new set of values to a hash (due to the way that operation is implemented internally, calling clear first and then assigning the values) will cause the empty callback to be also invoked. For instance:

  %a = (foo => 4),
  spy_hash(%a, empty => sub { say "the hash is empty" });

  # the empty callback is called here:
  %a = (foo => 4, doz => 'juas');




Salvador Fandiño, <>


Copyright (C) 2013 by Qindel Formaciñn y Servicios S.L.

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.14.2 or, at your option, any later version of Perl 5 you may have available.