Hash.pm 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. package Tie::Hash;
  2. our $VERSION = '1.05';
  3. =head1 NAME
  4. Tie::Hash, Tie::StdHash, Tie::ExtraHash - base class definitions for tied hashes
  5. =head1 SYNOPSIS
  6. package NewHash;
  7. require Tie::Hash;
  8. @ISA = qw(Tie::Hash);
  9. sub DELETE { ... } # Provides needed method
  10. sub CLEAR { ... } # Overrides inherited method
  11. package NewStdHash;
  12. require Tie::Hash;
  13. @ISA = qw(Tie::StdHash);
  14. # All methods provided by default, define
  15. # only those needing overrides
  16. # Accessors access the storage in %{$_[0]};
  17. # TIEHASH should return a reference to the actual storage
  18. sub DELETE { ... }
  19. package NewExtraHash;
  20. require Tie::Hash;
  21. @ISA = qw(Tie::ExtraHash);
  22. # All methods provided by default, define
  23. # only those needing overrides
  24. # Accessors access the storage in %{$_[0][0]};
  25. # TIEHASH should return an array reference with the first element
  26. # being the reference to the actual storage
  27. sub DELETE {
  28. $_[0][1]->('del', $_[0][0], $_[1]); # Call the report writer
  29. delete $_[0][0]->{$_[1]}; # $_[0]->SUPER::DELETE($_[1])
  30. }
  31. package main;
  32. tie %new_hash, 'NewHash';
  33. tie %new_std_hash, 'NewStdHash';
  34. tie %new_extra_hash, 'NewExtraHash',
  35. sub {warn "Doing \U$_[1]\E of $_[2].\n"};
  36. =head1 DESCRIPTION
  37. This module provides some skeletal methods for hash-tying classes. See
  38. L<perltie> for a list of the functions required in order to tie a hash
  39. to a package. The basic B<Tie::Hash> package provides a C<new> method, as well
  40. as methods C<TIEHASH>, C<EXISTS> and C<CLEAR>. The B<Tie::StdHash> and
  41. B<Tie::ExtraHash> packages
  42. provide most methods for hashes described in L<perltie> (the exceptions
  43. are C<UNTIE> and C<DESTROY>). They cause tied hashes to behave exactly like standard hashes,
  44. and allow for selective overwriting of methods. B<Tie::Hash> grandfathers the
  45. C<new> method: it is used if C<TIEHASH> is not defined
  46. in the case a class forgets to include a C<TIEHASH> method.
  47. For developers wishing to write their own tied hashes, the required methods
  48. are briefly defined below. See the L<perltie> section for more detailed
  49. descriptive, as well as example code:
  50. =over 4
  51. =item TIEHASH classname, LIST
  52. The method invoked by the command C<tie %hash, classname>. Associates a new
  53. hash instance with the specified class. C<LIST> would represent additional
  54. arguments (along the lines of L<AnyDBM_File> and compatriots) needed to
  55. complete the association.
  56. =item STORE this, key, value
  57. Store datum I<value> into I<key> for the tied hash I<this>.
  58. =item FETCH this, key
  59. Retrieve the datum in I<key> for the tied hash I<this>.
  60. =item FIRSTKEY this
  61. Return the first key in the hash.
  62. =item NEXTKEY this, lastkey
  63. Return the next key in the hash.
  64. =item EXISTS this, key
  65. Verify that I<key> exists with the tied hash I<this>.
  66. The B<Tie::Hash> implementation is a stub that simply croaks.
  67. =item DELETE this, key
  68. Delete the key I<key> from the tied hash I<this>.
  69. =item CLEAR this
  70. Clear all values from the tied hash I<this>.
  71. =item SCALAR this
  72. Returns what evaluating the hash in scalar context yields.
  73. B<Tie::Hash> does not implement this method (but B<Tie::StdHash>
  74. and B<Tie::ExtraHash> do).
  75. =back
  76. =head1 Inheriting from B<Tie::StdHash>
  77. The accessor methods assume that the actual storage for the data in the tied
  78. hash is in the hash referenced by C<tied(%tiedhash)>. Thus overwritten
  79. C<TIEHASH> method should return a hash reference, and the remaining methods
  80. should operate on the hash referenced by the first argument:
  81. package ReportHash;
  82. our @ISA = 'Tie::StdHash';
  83. sub TIEHASH {
  84. my $storage = bless {}, shift;
  85. warn "New ReportHash created, stored in $storage.\n";
  86. $storage
  87. }
  88. sub STORE {
  89. warn "Storing data with key $_[1] at $_[0].\n";
  90. $_[0]{$_[1]} = $_[2]
  91. }
  92. =head1 Inheriting from B<Tie::ExtraHash>
  93. The accessor methods assume that the actual storage for the data in the tied
  94. hash is in the hash referenced by C<(tied(%tiedhash))-E<gt>[0]>. Thus overwritten
  95. C<TIEHASH> method should return an array reference with the first
  96. element being a hash reference, and the remaining methods should operate on the
  97. hash C<< %{ $_[0]->[0] } >>:
  98. package ReportHash;
  99. our @ISA = 'Tie::ExtraHash';
  100. sub TIEHASH {
  101. my $class = shift;
  102. my $storage = bless [{}, @_], $class;
  103. warn "New ReportHash created, stored in $storage.\n";
  104. $storage;
  105. }
  106. sub STORE {
  107. warn "Storing data with key $_[1] at $_[0].\n";
  108. $_[0][0]{$_[1]} = $_[2]
  109. }
  110. The default C<TIEHASH> method stores "extra" arguments to tie() starting
  111. from offset 1 in the array referenced by C<tied(%tiedhash)>; this is the
  112. same storage algorithm as in TIEHASH subroutine above. Hence, a typical
  113. package inheriting from B<Tie::ExtraHash> does not need to overwrite this
  114. method.
  115. =head1 C<SCALAR>, C<UNTIE> and C<DESTROY>
  116. The methods C<UNTIE> and C<DESTROY> are not defined in B<Tie::Hash>,
  117. B<Tie::StdHash>, or B<Tie::ExtraHash>. Tied hashes do not require
  118. presence of these methods, but if defined, the methods will be called in
  119. proper time, see L<perltie>.
  120. C<SCALAR> is only defined in B<Tie::StdHash> and B<Tie::ExtraHash>.
  121. If needed, these methods should be defined by the package inheriting from
  122. B<Tie::Hash>, B<Tie::StdHash>, or B<Tie::ExtraHash>. See L<perltie/"SCALAR">
  123. to find out what happens when C<SCALAR> does not exist.
  124. =head1 MORE INFORMATION
  125. The packages relating to various DBM-related implementations (F<DB_File>,
  126. F<NDBM_File>, etc.) show examples of general tied hashes, as does the
  127. L<Config> module. While these do not utilize B<Tie::Hash>, they serve as
  128. good working examples.
  129. =cut
  130. use Carp;
  131. use warnings::register;
  132. sub new {
  133. my $pkg = shift;
  134. $pkg->TIEHASH(@_);
  135. }
  136. # Grandfather "new"
  137. sub TIEHASH {
  138. my $pkg = shift;
  139. my $pkg_new = $pkg -> can ('new');
  140. if ($pkg_new and $pkg ne __PACKAGE__) {
  141. my $my_new = __PACKAGE__ -> can ('new');
  142. if ($pkg_new == $my_new) {
  143. #
  144. # Prevent recursion
  145. #
  146. croak "$pkg must define either a TIEHASH() or a new() method";
  147. }
  148. warnings::warnif ("WARNING: calling ${pkg}->new since " .
  149. "${pkg}->TIEHASH is missing");
  150. $pkg -> new (@_);
  151. }
  152. else {
  153. croak "$pkg doesn't define a TIEHASH method";
  154. }
  155. }
  156. sub EXISTS {
  157. my $pkg = ref $_[0];
  158. croak "$pkg doesn't define an EXISTS method";
  159. }
  160. sub CLEAR {
  161. my $self = shift;
  162. my $key = $self->FIRSTKEY(@_);
  163. my @keys;
  164. while (defined $key) {
  165. push @keys, $key;
  166. $key = $self->NEXTKEY(@_, $key);
  167. }
  168. foreach $key (@keys) {
  169. $self->DELETE(@_, $key);
  170. }
  171. }
  172. # The Tie::StdHash package implements standard perl hash behaviour.
  173. # It exists to act as a base class for classes which only wish to
  174. # alter some parts of their behaviour.
  175. package Tie::StdHash;
  176. # @ISA = qw(Tie::Hash); # would inherit new() only
  177. sub TIEHASH { bless {}, $_[0] }
  178. sub STORE { $_[0]->{$_[1]} = $_[2] }
  179. sub FETCH { $_[0]->{$_[1]} }
  180. sub FIRSTKEY { my $a = scalar keys %{$_[0]}; each %{$_[0]} }
  181. sub NEXTKEY { each %{$_[0]} }
  182. sub EXISTS { exists $_[0]->{$_[1]} }
  183. sub DELETE { delete $_[0]->{$_[1]} }
  184. sub CLEAR { %{$_[0]} = () }
  185. sub SCALAR { scalar %{$_[0]} }
  186. package Tie::ExtraHash;
  187. sub TIEHASH { my $p = shift; bless [{}, @_], $p }
  188. sub STORE { $_[0][0]{$_[1]} = $_[2] }
  189. sub FETCH { $_[0][0]{$_[1]} }
  190. sub FIRSTKEY { my $a = scalar keys %{$_[0][0]}; each %{$_[0][0]} }
  191. sub NEXTKEY { each %{$_[0][0]} }
  192. sub EXISTS { exists $_[0][0]->{$_[1]} }
  193. sub DELETE { delete $_[0][0]->{$_[1]} }
  194. sub CLEAR { %{$_[0][0]} = () }
  195. sub SCALAR { scalar %{$_[0][0]} }
  196. 1;