5 use Data::Util qw(sv_readonly_flag);
9 our @ISA = qw(Exporter);
10 our @EXPORT_OK = qw(lock_keys unlock_keys lock_value unlock_value
18 Hash::Util - A selection of general-utility hash subroutines
22 use Hash::Util qw(lock_keys unlock_keys
23 lock_value unlock_value
27 %hash = (foo => 42, bar => 23);
29 lock_keys(%hash, @keyset);
32 lock_value (%hash, 'foo');
33 unlock_value(%hash, 'foo');
41 C<Hash::Util> contains special functions for manipulating hashes that
42 don't really warrant a keyword.
44 By default C<Hash::Util> does not export anything.
46 =head2 Restricted hashes
48 5.8.0 introduces the ability to restrict a hash to a certain set of
49 keys. No keys outside of this set can be added. It also introduces
50 the ability to lock an individual key so it cannot be deleted and the
51 value cannot be changed.
53 This is intended to largely replace the deprecated pseudo-hashes.
62 lock_keys(%hash, @keys);
66 Restricts the given %hash's set of keys to @keys. If @keys is not
67 given it restricts it to its current keyset. No more keys can be
68 added. delete() and exists() will still work, but it does not effect
69 the set of allowed keys.
71 Removes the restriction on the %hash's keyset.
75 sub lock_keys (\%;@) {
76 my($hash, @keys) = @_;
79 my %keys = map { ($_ => 1) } @keys;
80 my %original_keys = map { ($_ => 1) } keys %$hash;
81 foreach my $k (keys %original_keys) {
82 die sprintf "Hash has key '$k' which is not in the new key ".
83 "set at %s line %d\n", (caller)[1,2]
87 foreach my $k (@keys) {
88 $hash->{$k} = undef unless exists $hash->{$k};
90 sv_readonly_flag %$hash, 1;
92 foreach my $k (@keys) {
93 delete $hash->{$k} unless $original_keys{$k};
97 sv_readonly_flag %$hash, 1;
103 sub unlock_keys (\%) {
106 sv_readonly_flag %$hash, 0;
114 lock_key (%hash, $key);
115 unlock_key(%hash, $key);
117 Locks and unlocks an individual key of a hash. The value of a locked
118 key cannot be changed.
120 %hash must have already been locked for this to have useful effect.
124 sub lock_value (\%$) {
125 my($hash, $key) = @_;
126 carp "Cannot usefully lock values in an unlocked hash"
127 unless sv_readonly_flag %$hash;
128 sv_readonly_flag $hash->{$key}, 1;
131 sub unlock_value (\%$) {
132 my($hash, $key) = @_;
133 sv_readonly_flag $hash->{$key}, 0;
144 lock_hash() locks an entire hash, making all keys and values readonly.
145 No value can be changed, no keys can be added or deleted.
147 unlock_hash() does the opposite. All keys and values are made
148 read/write. All values can be changed and keys can be added and
158 foreach my $key (keys %$hash) {
159 lock_value(%$hash, $key);
165 sub unlock_hash (\%) {
168 foreach my $key (keys %$hash) {
169 unlock_value(%$hash, $key);
182 Michael G Schwern <schwern@pobox.com> on top of code by Nick
183 Ing-Simmons and Jeffrey Friedl.
187 L<Scalar::Util>, L<List::Util>, L<Hash::Util>