Help language development. Donate to The Perl Foundation

WriteOnceHash cpan:ELIZABETH last updated on 2021-01-31



WriteOnceHash - be a Hash in which each key can only be set once


use WriteOnceHash;

# bind to predefined class
my %woh is WriteOnceHash;
%woh<a> = 5; # ok
%woh<a> = 1; # throws

    when X::Hash::WriteOnce {
        say "Sorry, already set {.key} before";

# mix in role on anything that does Associative
my %owoh{Any} does WriteOnce;


This module makes an WriteOnceHash class available that can be used instead of the normal Hash. The only difference with a normal Hash is, is that if an attempt is made to set the value of a key that has already been set before, an exception is thrown rather than just overwriting the key in the Hash.

Also binding to non-existing keys in the hash, and then assigning to the obtained container, will only work once. Iterating over values of the hash will only yield values, not containers (as a normal Hash would).

Also exports a X::Hash::WriteOnce error class that will be thrown if an attempt is made to set a key again.

The underlying WriteOnce role is also exported that can be used on objects that perform the Associative role that are not Hash (such as object hashes).


Elizabeth Mattijsen [email protected]

Source can be located at: . Comments and Pull Requests are welcome.


Copyright 2018,2020,2021 Elizabeth Mattijsen

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.