Rand Stats

Hash::MutableKeys

zef:lizmat

Actions Status Actions Status Actions Status

NAME

Hash::MutableKeys - provide .keys method with mutable keys

SYNOPSIS

use Hash::MutableKeys;

my %h is Hash::MutableKeys = a => (1,2,3), b => 666;
say %h;  # {a => (1 2 3), b => 666}

$_ .= uc for %h.keys;  # make all keys uppercase
say %h;  # {A => (1 2 3), B => 666}

DESCRIPTION

The Hash::MutableKeys distribution provides a role that can be used as a replacement class for Hashes.

The only functional difference with ordinary Hashes is that the <.keys> method provides a mutable representation of the key. When a key is altered, the value of the key is pushed to the new value of the key and removed from the old key.

By default, values will be "push"ed to the new key. One can change this by parameterizing the role by specifying the name of the method that should be used. A sensible option would be "append". But one could go crazy by providing other names (possibly of methods that are mixed in by the developer).

use Hash::MutableKeys;

my %h is Hash::MutableKeys["append"] = a => (1,2,3), b => 666;
say %h;  # {a => (1 2 3), b => 666}

$_ = "foo" for %h.keys.sort;  # combine all values in "foo" key
say %h;  # {foo => [1 2 3 666]}

Originally this distribution was started as an example of using a Proxy. But maybe it is more useful than that after all.

AUTHOR

Elizabeth Mattijsen liz@raku.rocks

Source can be located at: https://github.com/lizmat/Hash-MutableKeys . Comments and Pull Requests are welcome.

If you like this module, or what I'm doing more generally, committing to a small sponsorship would mean a great deal to me!

COPYRIGHT AND LICENSE

Copyright 2026 Elizabeth Mattijsen

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