7 use warnings::register;
8 use Scalar::Util qw(reftype);
11 our @ISA = qw(Exporter);
17 lock_value unlock_value
19 lock_keys_plus hash_locked
20 hidden_keys legal_keys
22 lock_ref_keys unlock_ref_keys
23 lock_ref_value unlock_ref_value
24 lock_hashref unlock_hashref
25 lock_ref_keys_plus hashref_locked
26 hidden_ref_keys legal_ref_keys
33 local @ISA = qw(DynaLoader);
34 bootstrap Hash::Util $VERSION;
38 if ( grep /fieldhash/, @_ ) {
39 require Hash::Util::FieldHash;
40 Hash::Util::FieldHash->import(':all'); # for re-export
43 goto &Exporter::import;
49 Hash::Util - A selection of general-utility hash subroutines
55 use Hash::Util qw(fieldhash fieldhashes);
57 # Create a single field hash
60 # Create three at once...
61 fieldhashes \ my(%foo, %bar, %baz);
63 fieldhashes @hashrefs;
70 lock_value unlock_value
72 lock_keys_plus hash_locked
73 hidden_keys legal_keys
76 %hash = (foo => 42, bar => 23);
77 # Ways to restrict a hash
79 lock_keys(%hash, @keyset);
80 lock_keys_plus(%hash, @additional_keys);
82 #Ways to inspect the properties of a restricted hash
83 my @legal=legal_keys(%hash);
84 my @hidden=hidden_keys(%hash);
85 my $ref=all_keys(%hash,@keys,@hidden);
86 my $is_locked=hash_locked(%hash);
88 #Remove restrictions on the hash
91 #Lock individual values in a hash
92 lock_value (%hash, 'foo');
93 unlock_value(%hash, 'foo');
95 #Ways to change the restrictions on both keys and values
99 my $hashes_are_randomised = hash_seed() != 0;
103 C<Hash::Util> contains special functions for manipulating hashes that
104 don't really warrant a keyword.
106 By default C<Hash::Util> does not export anything.
110 Field hashes are designed to maintain an association of a reference
111 with a value. The association is independent of the bless status of
112 the key, it is thread safe and garbage-collected. These properties
113 are desirable in the construction of inside-out classes.
115 When used with keys that are plain scalars (not references), field
116 hashes behave like normal hashes.
118 Field hashes are defined in a separate module for which C<Hash::Util>
119 is a front end. For a detailed description see L<Hash::Util::FieldHash>.
121 =head2 Restricted hashes
123 5.8.0 introduces the ability to restrict a hash to a certain set of
124 keys. No keys outside of this set can be added. It also introduces
125 the ability to lock an individual key so it cannot be deleted and the
126 ability to ensure that an individual value cannot be changed.
128 This is intended to largely replace the deprecated pseudo-hashes.
137 lock_keys(%hash, @keys);
139 Restricts the given %hash's set of keys to @keys. If @keys is not
140 given it restricts it to its current keyset. No more keys can be
141 added. delete() and exists() will still work, but will not alter
142 the set of allowed keys. B<Note>: the current implementation prevents
143 the hash from being bless()ed while it is in a locked state. Any attempt
144 to do so will raise an exception. Of course you can still bless()
145 the hash before you call lock_keys() so this shouldn't be a problem.
149 Removes the restriction on the %hash's keyset.
151 B<Note> that if any of the values of the hash have been locked they will not be unlocked
152 after this sub executes.
154 Both routines return a reference to the hash operated on.
159 my($hash, @keys) = @_;
161 Internals::hv_clear_placeholders %$hash;
163 my %keys = map { ($_ => 1) } @keys;
164 my %original_keys = map { ($_ => 1) } keys %$hash;
165 foreach my $k (keys %original_keys) {
166 croak "Hash has key '$k' which is not in the new key set"
170 foreach my $k (@keys) {
171 $hash->{$k} = undef unless exists $hash->{$k};
173 Internals::SvREADONLY %$hash, 1;
175 foreach my $k (@keys) {
176 delete $hash->{$k} unless $original_keys{$k};
180 Internals::SvREADONLY %$hash, 1;
186 sub unlock_ref_keys {
189 Internals::SvREADONLY %$hash, 0;
193 sub lock_keys (\%;@) { lock_ref_keys(@_) }
194 sub unlock_keys (\%) { unlock_ref_keys(@_) }
196 =item B<lock_keys_plus>
198 lock_keys_plus(%hash,@additional_keys)
200 Similar to C<lock_keys()>, with the difference being that the optional key list
201 specifies keys that may or may not be already in the hash. Essentially this is
204 lock_keys(%hash,@additional_keys,keys %hash);
206 Returns a reference to %hash
211 sub lock_ref_keys_plus {
214 Internals::hv_clear_placeholders(%$hash);
215 foreach my $key (@keys) {
216 unless (exists($hash->{$key})) {
221 Internals::SvREADONLY(%$hash,1);
222 delete @{$hash}{@delete};
226 sub lock_keys_plus(\%;@) { lock_ref_keys_plus(@_) }
231 =item B<unlock_value>
233 lock_value (%hash, $key);
234 unlock_value(%hash, $key);
236 Locks and unlocks the value for an individual key of a hash. The value of a
237 locked key cannot be changed.
239 Unless %hash has already been locked the key/value could be deleted
240 regardless of this setting.
242 Returns a reference to the %hash.
247 my($hash, $key) = @_;
248 # I'm doubtful about this warning, as it seems not to be true.
249 # Marking a value in the hash as RO is useful, regardless
250 # of the status of the hash itself.
251 carp "Cannot usefully lock values in an unlocked hash"
252 if !Internals::SvREADONLY(%$hash) && warnings::enabled;
253 Internals::SvREADONLY $hash->{$key}, 1;
257 sub unlock_ref_value {
258 my($hash, $key) = @_;
259 Internals::SvREADONLY $hash->{$key}, 0;
263 sub lock_value (\%$) { lock_ref_value(@_) }
264 sub unlock_value (\%$) { unlock_ref_value(@_) }
273 lock_hash() locks an entire hash, making all keys and values readonly.
274 No value can be changed, no keys can be added or deleted.
278 unlock_hash() does the opposite of lock_hash(). All keys and values
279 are made writable. All values can be changed and keys can be added
282 Returns a reference to the %hash.
289 lock_ref_keys($hash);
291 foreach my $value (values %$hash) {
292 Internals::SvREADONLY($value,1);
301 foreach my $value (values %$hash) {
302 Internals::SvREADONLY($value, 0);
305 unlock_ref_keys($hash);
310 sub lock_hash (\%) { lock_hashref(@_) }
311 sub unlock_hash (\%) { unlock_hashref(@_) }
313 =item B<lock_hash_recurse>
315 =item B<unlock_hash_recurse>
317 lock_hash_recurse(%hash);
319 lock_hash() locks an entire hash and any hashes it references recursively,
320 making all keys and values readonly. No value can be changed, no keys can
323 B<Only> recurses into hashes that are referenced by another hash. Thus a
324 Hash of Hashes (HoH) will all be restricted, but a Hash of Arrays of Hashes
325 (HoAoH) will only have the top hash restricted.
327 unlock_hash_recurse(%hash);
329 unlock_hash_recurse() does the opposite of lock_hash_recurse(). All keys and
330 values are made writable. All values can be changed and keys can be added
331 and deleted. Identical recursion restrictions apply as to lock_hash_recurse().
333 Returns a reference to the %hash.
337 sub lock_hashref_recurse {
340 lock_ref_keys($hash);
341 foreach my $value (values %$hash) {
342 if (reftype($value) eq 'HASH') {
343 lock_hashref_recurse($value);
345 Internals::SvREADONLY($value,1);
350 sub unlock_hashref_recurse {
353 foreach my $value (values %$hash) {
354 if (reftype($value) eq 'HASH') {
355 unlock_hashref_recurse($value);
357 Internals::SvREADONLY($value,1);
359 unlock_ref_keys($hash);
363 sub lock_hash_recurse (\%) { lock_hashref_recurse(@_) }
364 sub unlock_hash_recurse (\%) { unlock_hashref_recurse(@_) }
367 =item B<hash_unlocked>
369 hash_unlocked(%hash) and print "Hash is unlocked!\n";
371 Returns true if the hash and its keys are unlocked.
375 sub hashref_unlocked {
377 return Internals::SvREADONLY($hash)
380 sub hash_unlocked(\%) { hashref_unlocked(@_) }
382 =for demerphqs_editor
384 sub hidden_ref_keys{}
389 sub legal_keys(\%) { legal_ref_keys(@_) }
390 sub hidden_keys(\%){ hidden_ref_keys(@_) }
394 my @keys=legal_keys(%hash);
396 Returns a list of the keys that are legal in a restricted hash.
397 In the case of an unrestricted hash this is identical to calling
402 my @keys=hidden_keys(%hash);
404 Returns a list of the keys that are legal in a restricted hash but
405 do not have a value associated to them. Thus if 'foo' is a
406 "hidden" key of the %hash it will return false for both C<defined>
409 In the case of an unrestricted hash this will return an empty list.
411 B<NOTE> this is an experimental feature that is heavily dependent
412 on the current implementation of restricted hashes. Should the
413 implementation change this routine may become meaningless in which
414 case it will return an empty list.
418 all_keys(%hash,@keys,@hidden);
420 Populates the arrays @keys with the all the keys that would pass
421 an C<exists> tests, and populates @hidden with the remaining legal
422 keys that have not been utilized.
424 Returns a reference to the hash.
426 In the case of an unrestricted hash this will be equivelent to
434 B<NOTE> this is an experimental feature that is heavily dependent
435 on the current implementation of restricted hashes. Should the
436 implementation change this routine may become meaningless in which
437 case it will behave identically to how it would behave on an
442 my $hash_seed = hash_seed();
444 hash_seed() returns the seed number used to randomise hash ordering.
445 Zero means the "traditional" random hash ordering, non-zero means the
446 new even more random hash ordering introduced in Perl 5.8.1.
448 B<Note that the hash seed is sensitive information>: by knowing it one
449 can craft a denial-of-service attack against Perl code, even remotely,
450 see L<perlsec/"Algorithmic Complexity Attacks"> for more information.
451 B<Do not disclose the hash seed> to people who don't need to know it.
452 See also L<perlrun/PERL_HASH_SEED_DEBUG>.
457 Internals::rehash_seed();
463 hv_store(%hash,$key,$sv) or die "Failed to alias!";
465 print $sv; # prints 1
467 Stores an alias to a variable in a hash instead of copying the value.
471 =head2 Operating on references to hashes.
473 Most subroutines documented in this module have equivelent versions
474 that operate on references to hashes instead of native hashes.
475 The following is a list of these subs. They are identical except
476 in name and in that instead of taking a %hash they take a $hashref,
477 and additionally are not prototyped.
483 =item unlock_ref_keys
485 =item lock_ref_keys_plus
489 =item unlock_ref_value
495 =item lock_hashref_recurse
497 =item unlock_hashref_recurse
499 =item hash_ref_unlocked
503 =item hidden_ref_keys
509 Note that the trapping of the restricted operations is not atomic:
512 eval { %hash = (illegal_key => 1) }
514 leaves the C<%hash> empty rather than with its original contents.
518 The interface exposed by this module is very close to the current
519 imlementation of restricted hashes. Over time it is expected that
520 this behavior will be extended and the interface abstracted further.
524 Michael G Schwern <schwern@pobox.com> on top of code by Nick
525 Ing-Simmons and Jeffrey Friedl.
527 hv_store() is from Array::RefElem, Copyright 2000 Gisle Aas.
529 Additional code by Yves Orton.
533 L<Scalar::Util>, L<List::Util>, L<Hash::Util>,
534 and L<perlsec/"Algorithmic Complexity Attacks">.