Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1084 lines
34 KiB

  1. =head1 NAME
  2. perltie - how to hide an object class in a simple variable
  3. =head1 SYNOPSIS
  4. tie VARIABLE, CLASSNAME, LIST
  5. $object = tied VARIABLE
  6. untie VARIABLE
  7. =head1 DESCRIPTION
  8. Prior to release 5.0 of Perl, a programmer could use dbmopen()
  9. to connect an on-disk database in the standard Unix dbm(3x)
  10. format magically to a %HASH in their program. However, their Perl was either
  11. built with one particular dbm library or another, but not both, and
  12. you couldn't extend this mechanism to other packages or types of variables.
  13. Now you can.
  14. The tie() function binds a variable to a class (package) that will provide
  15. the implementation for access methods for that variable. Once this magic
  16. has been performed, accessing a tied variable automatically triggers
  17. method calls in the proper class. The complexity of the class is
  18. hidden behind magic methods calls. The method names are in ALL CAPS,
  19. which is a convention that Perl uses to indicate that they're called
  20. implicitly rather than explicitly--just like the BEGIN() and END()
  21. functions.
  22. In the tie() call, C<VARIABLE> is the name of the variable to be
  23. enchanted. C<CLASSNAME> is the name of a class implementing objects of
  24. the correct type. Any additional arguments in the C<LIST> are passed to
  25. the appropriate constructor method for that class--meaning TIESCALAR(),
  26. TIEARRAY(), TIEHASH(), or TIEHANDLE(). (Typically these are arguments
  27. such as might be passed to the dbminit() function of C.) The object
  28. returned by the "new" method is also returned by the tie() function,
  29. which would be useful if you wanted to access other methods in
  30. C<CLASSNAME>. (You don't actually have to return a reference to a right
  31. "type" (e.g., HASH or C<CLASSNAME>) so long as it's a properly blessed
  32. object.) You can also retrieve a reference to the underlying object
  33. using the tied() function.
  34. Unlike dbmopen(), the tie() function will not C<use> or C<require> a module
  35. for you--you need to do that explicitly yourself.
  36. =head2 Tying Scalars
  37. A class implementing a tied scalar should define the following methods:
  38. TIESCALAR, FETCH, STORE, and possibly UNTIE and/or DESTROY.
  39. Let's look at each in turn, using as an example a tie class for
  40. scalars that allows the user to do something like:
  41. tie $his_speed, 'Nice', getppid();
  42. tie $my_speed, 'Nice', $$;
  43. And now whenever either of those variables is accessed, its current
  44. system priority is retrieved and returned. If those variables are set,
  45. then the process's priority is changed!
  46. We'll use Jarkko Hietaniemi <F<[email protected]>>'s BSD::Resource class (not
  47. included) to access the PRIO_PROCESS, PRIO_MIN, and PRIO_MAX constants
  48. from your system, as well as the getpriority() and setpriority() system
  49. calls. Here's the preamble of the class.
  50. package Nice;
  51. use Carp;
  52. use BSD::Resource;
  53. use strict;
  54. $Nice::DEBUG = 0 unless defined $Nice::DEBUG;
  55. =over 4
  56. =item TIESCALAR classname, LIST
  57. This is the constructor for the class. That means it is
  58. expected to return a blessed reference to a new scalar
  59. (probably anonymous) that it's creating. For example:
  60. sub TIESCALAR {
  61. my $class = shift;
  62. my $pid = shift || $$; # 0 means me
  63. if ($pid !~ /^\d+$/) {
  64. carp "Nice::Tie::Scalar got non-numeric pid $pid" if $^W;
  65. return undef;
  66. }
  67. unless (kill 0, $pid) { # EPERM or ERSCH, no doubt
  68. carp "Nice::Tie::Scalar got bad pid $pid: $!" if $^W;
  69. return undef;
  70. }
  71. return bless \$pid, $class;
  72. }
  73. This tie class has chosen to return an error rather than raising an
  74. exception if its constructor should fail. While this is how dbmopen() works,
  75. other classes may well not wish to be so forgiving. It checks the global
  76. variable C<$^W> to see whether to emit a bit of noise anyway.
  77. =item FETCH this
  78. This method will be triggered every time the tied variable is accessed
  79. (read). It takes no arguments beyond its self reference, which is the
  80. object representing the scalar we're dealing with. Because in this case
  81. we're using just a SCALAR ref for the tied scalar object, a simple $$self
  82. allows the method to get at the real value stored there. In our example
  83. below, that real value is the process ID to which we've tied our variable.
  84. sub FETCH {
  85. my $self = shift;
  86. confess "wrong type" unless ref $self;
  87. croak "usage error" if @_;
  88. my $nicety;
  89. local($!) = 0;
  90. $nicety = getpriority(PRIO_PROCESS, $$self);
  91. if ($!) { croak "getpriority failed: $!" }
  92. return $nicety;
  93. }
  94. This time we've decided to blow up (raise an exception) if the renice
  95. fails--there's no place for us to return an error otherwise, and it's
  96. probably the right thing to do.
  97. =item STORE this, value
  98. This method will be triggered every time the tied variable is set
  99. (assigned). Beyond its self reference, it also expects one (and only one)
  100. argument--the new value the user is trying to assign.
  101. sub STORE {
  102. my $self = shift;
  103. confess "wrong type" unless ref $self;
  104. my $new_nicety = shift;
  105. croak "usage error" if @_;
  106. if ($new_nicety < PRIO_MIN) {
  107. carp sprintf
  108. "WARNING: priority %d less than minimum system priority %d",
  109. $new_nicety, PRIO_MIN if $^W;
  110. $new_nicety = PRIO_MIN;
  111. }
  112. if ($new_nicety > PRIO_MAX) {
  113. carp sprintf
  114. "WARNING: priority %d greater than maximum system priority %d",
  115. $new_nicety, PRIO_MAX if $^W;
  116. $new_nicety = PRIO_MAX;
  117. }
  118. unless (defined setpriority(PRIO_PROCESS, $$self, $new_nicety)) {
  119. confess "setpriority failed: $!";
  120. }
  121. return $new_nicety;
  122. }
  123. =item UNTIE this
  124. This method will be triggered when the C<untie> occurs. This can be useful
  125. if the class needs to know when no further calls will be made. (Except DESTROY
  126. of course.) See below for more details.
  127. =item DESTROY this
  128. This method will be triggered when the tied variable needs to be destructed.
  129. As with other object classes, such a method is seldom necessary, because Perl
  130. deallocates its moribund object's memory for you automatically--this isn't
  131. C++, you know. We'll use a DESTROY method here for debugging purposes only.
  132. sub DESTROY {
  133. my $self = shift;
  134. confess "wrong type" unless ref $self;
  135. carp "[ Nice::DESTROY pid $$self ]" if $Nice::DEBUG;
  136. }
  137. =back
  138. That's about all there is to it. Actually, it's more than all there
  139. is to it, because we've done a few nice things here for the sake
  140. of completeness, robustness, and general aesthetics. Simpler
  141. TIESCALAR classes are certainly possible.
  142. =head2 Tying Arrays
  143. A class implementing a tied ordinary array should define the following
  144. methods: TIEARRAY, FETCH, STORE, FETCHSIZE, STORESIZE and perhaps UNTIE and/or DESTROY.
  145. FETCHSIZE and STORESIZE are used to provide C<$#array> and
  146. equivalent C<scalar(@array)> access.
  147. The methods POP, PUSH, SHIFT, UNSHIFT, SPLICE, DELETE, and EXISTS are
  148. required if the perl operator with the corresponding (but lowercase) name
  149. is to operate on the tied array. The B<Tie::Array> class can be used as a
  150. base class to implement the first five of these in terms of the basic
  151. methods above. The default implementations of DELETE and EXISTS in
  152. B<Tie::Array> simply C<croak>.
  153. In addition EXTEND will be called when perl would have pre-extended
  154. allocation in a real array.
  155. For this discussion, we'll implement an array whose elements are a fixed
  156. size at creation. If you try to create an element larger than the fixed
  157. size, you'll take an exception. For example:
  158. use FixedElem_Array;
  159. tie @array, 'FixedElem_Array', 3;
  160. $array[0] = 'cat'; # ok.
  161. $array[1] = 'dogs'; # exception, length('dogs') > 3.
  162. The preamble code for the class is as follows:
  163. package FixedElem_Array;
  164. use Carp;
  165. use strict;
  166. =over 4
  167. =item TIEARRAY classname, LIST
  168. This is the constructor for the class. That means it is expected to
  169. return a blessed reference through which the new array (probably an
  170. anonymous ARRAY ref) will be accessed.
  171. In our example, just to show you that you don't I<really> have to return an
  172. ARRAY reference, we'll choose a HASH reference to represent our object.
  173. A HASH works out well as a generic record type: the C<{ELEMSIZE}> field will
  174. store the maximum element size allowed, and the C<{ARRAY}> field will hold the
  175. true ARRAY ref. If someone outside the class tries to dereference the
  176. object returned (doubtless thinking it an ARRAY ref), they'll blow up.
  177. This just goes to show you that you should respect an object's privacy.
  178. sub TIEARRAY {
  179. my $class = shift;
  180. my $elemsize = shift;
  181. if ( @_ || $elemsize =~ /\D/ ) {
  182. croak "usage: tie ARRAY, '" . __PACKAGE__ . "', elem_size";
  183. }
  184. return bless {
  185. ELEMSIZE => $elemsize,
  186. ARRAY => [],
  187. }, $class;
  188. }
  189. =item FETCH this, index
  190. This method will be triggered every time an individual element the tied array
  191. is accessed (read). It takes one argument beyond its self reference: the
  192. index whose value we're trying to fetch.
  193. sub FETCH {
  194. my $self = shift;
  195. my $index = shift;
  196. return $self->{ARRAY}->[$index];
  197. }
  198. If a negative array index is used to read from an array, the index
  199. will be translated to a positive one internally by calling FETCHSIZE
  200. before being passed to FETCH.
  201. As you may have noticed, the name of the FETCH method (et al.) is the same
  202. for all accesses, even though the constructors differ in names (TIESCALAR
  203. vs TIEARRAY). While in theory you could have the same class servicing
  204. several tied types, in practice this becomes cumbersome, and it's easiest
  205. to keep them at simply one tie type per class.
  206. =item STORE this, index, value
  207. This method will be triggered every time an element in the tied array is set
  208. (written). It takes two arguments beyond its self reference: the index at
  209. which we're trying to store something and the value we're trying to put
  210. there.
  211. In our example, C<undef> is really C<$self-E<gt>{ELEMSIZE}> number of
  212. spaces so we have a little more work to do here:
  213. sub STORE {
  214. my $self = shift;
  215. my( $index, $value ) = @_;
  216. if ( length $value > $self->{ELEMSIZE} ) {
  217. croak "length of $value is greater than $self->{ELEMSIZE}";
  218. }
  219. # fill in the blanks
  220. $self->EXTEND( $index ) if $index > $self->FETCHSIZE();
  221. # right justify to keep element size for smaller elements
  222. $self->{ARRAY}->[$index] = sprintf "%$self->{ELEMSIZE}s", $value;
  223. }
  224. Negative indexes are treated the same as with FETCH.
  225. =item FETCHSIZE this
  226. Returns the total number of items in the tied array associated with
  227. object I<this>. (Equivalent to C<scalar(@array)>). For example:
  228. sub FETCHSIZE {
  229. my $self = shift;
  230. return scalar @{$self->{ARRAY}};
  231. }
  232. =item STORESIZE this, count
  233. Sets the total number of items in the tied array associated with
  234. object I<this> to be I<count>. If this makes the array larger then
  235. class's mapping of C<undef> should be returned for new positions.
  236. If the array becomes smaller then entries beyond count should be
  237. deleted.
  238. In our example, 'undef' is really an element containing
  239. C<$self-E<gt>{ELEMSIZE}> number of spaces. Observe:
  240. sub STORESIZE {
  241. my $self = shift;
  242. my $count = shift;
  243. if ( $count > $self->FETCHSIZE() ) {
  244. foreach ( $count - $self->FETCHSIZE() .. $count ) {
  245. $self->STORE( $_, '' );
  246. }
  247. } elsif ( $count < $self->FETCHSIZE() ) {
  248. foreach ( 0 .. $self->FETCHSIZE() - $count - 2 ) {
  249. $self->POP();
  250. }
  251. }
  252. }
  253. =item EXTEND this, count
  254. Informative call that array is likely to grow to have I<count> entries.
  255. Can be used to optimize allocation. This method need do nothing.
  256. In our example, we want to make sure there are no blank (C<undef>)
  257. entries, so C<EXTEND> will make use of C<STORESIZE> to fill elements
  258. as needed:
  259. sub EXTEND {
  260. my $self = shift;
  261. my $count = shift;
  262. $self->STORESIZE( $count );
  263. }
  264. =item EXISTS this, key
  265. Verify that the element at index I<key> exists in the tied array I<this>.
  266. In our example, we will determine that if an element consists of
  267. C<$self-E<gt>{ELEMSIZE}> spaces only, it does not exist:
  268. sub EXISTS {
  269. my $self = shift;
  270. my $index = shift;
  271. return 0 if ! defined $self->{ARRAY}->[$index] ||
  272. $self->{ARRAY}->[$index] eq ' ' x $self->{ELEMSIZE};
  273. return 1;
  274. }
  275. =item DELETE this, key
  276. Delete the element at index I<key> from the tied array I<this>.
  277. In our example, a deleted item is C<$self->{ELEMSIZE}> spaces:
  278. sub DELETE {
  279. my $self = shift;
  280. my $index = shift;
  281. return $self->STORE( $index, '' );
  282. }
  283. =item CLEAR this
  284. Clear (remove, delete, ...) all values from the tied array associated with
  285. object I<this>. For example:
  286. sub CLEAR {
  287. my $self = shift;
  288. return $self->{ARRAY} = [];
  289. }
  290. =item PUSH this, LIST
  291. Append elements of I<LIST> to the array. For example:
  292. sub PUSH {
  293. my $self = shift;
  294. my @list = @_;
  295. my $last = $self->FETCHSIZE();
  296. $self->STORE( $last + $_, $list[$_] ) foreach 0 .. $#list;
  297. return $self->FETCHSIZE();
  298. }
  299. =item POP this
  300. Remove last element of the array and return it. For example:
  301. sub POP {
  302. my $self = shift;
  303. return pop @{$self->{ARRAY}};
  304. }
  305. =item SHIFT this
  306. Remove the first element of the array (shifting other elements down)
  307. and return it. For example:
  308. sub SHIFT {
  309. my $self = shift;
  310. return shift @{$self->{ARRAY}};
  311. }
  312. =item UNSHIFT this, LIST
  313. Insert LIST elements at the beginning of the array, moving existing elements
  314. up to make room. For example:
  315. sub UNSHIFT {
  316. my $self = shift;
  317. my @list = @_;
  318. my $size = scalar( @list );
  319. # make room for our list
  320. @{$self->{ARRAY}}[ $size .. $#{$self->{ARRAY}} + $size ]
  321. = @{$self->{ARRAY}};
  322. $self->STORE( $_, $list[$_] ) foreach 0 .. $#list;
  323. }
  324. =item SPLICE this, offset, length, LIST
  325. Perform the equivalent of C<splice> on the array.
  326. I<offset> is optional and defaults to zero, negative values count back
  327. from the end of the array.
  328. I<length> is optional and defaults to rest of the array.
  329. I<LIST> may be empty.
  330. Returns a list of the original I<length> elements at I<offset>.
  331. In our example, we'll use a little shortcut if there is a I<LIST>:
  332. sub SPLICE {
  333. my $self = shift;
  334. my $offset = shift || 0;
  335. my $length = shift || $self->FETCHSIZE() - $offset;
  336. my @list = ();
  337. if ( @_ ) {
  338. tie @list, __PACKAGE__, $self->{ELEMSIZE};
  339. @list = @_;
  340. }
  341. return splice @{$self->{ARRAY}}, $offset, $length, @list;
  342. }
  343. =item UNTIE this
  344. Will be called when C<untie> happens. (See below.)
  345. =item DESTROY this
  346. This method will be triggered when the tied variable needs to be destructed.
  347. As with the scalar tie class, this is almost never needed in a
  348. language that does its own garbage collection, so this time we'll
  349. just leave it out.
  350. =back
  351. =head2 Tying Hashes
  352. Hashes were the first Perl data type to be tied (see dbmopen()). A class
  353. implementing a tied hash should define the following methods: TIEHASH is
  354. the constructor. FETCH and STORE access the key and value pairs. EXISTS
  355. reports whether a key is present in the hash, and DELETE deletes one.
  356. CLEAR empties the hash by deleting all the key and value pairs. FIRSTKEY
  357. and NEXTKEY implement the keys() and each() functions to iterate over all
  358. the keys. UNTIE is called when C<untie> happens, and DESTROY is called when
  359. the tied variable is garbage collected.
  360. If this seems like a lot, then feel free to inherit from merely the
  361. standard Tie::Hash module for most of your methods, redefining only the
  362. interesting ones. See L<Tie::Hash> for details.
  363. Remember that Perl distinguishes between a key not existing in the hash,
  364. and the key existing in the hash but having a corresponding value of
  365. C<undef>. The two possibilities can be tested with the C<exists()> and
  366. C<defined()> functions.
  367. Here's an example of a somewhat interesting tied hash class: it gives you
  368. a hash representing a particular user's dot files. You index into the hash
  369. with the name of the file (minus the dot) and you get back that dot file's
  370. contents. For example:
  371. use DotFiles;
  372. tie %dot, 'DotFiles';
  373. if ( $dot{profile} =~ /MANPATH/ ||
  374. $dot{login} =~ /MANPATH/ ||
  375. $dot{cshrc} =~ /MANPATH/ )
  376. {
  377. print "you seem to set your MANPATH\n";
  378. }
  379. Or here's another sample of using our tied class:
  380. tie %him, 'DotFiles', 'daemon';
  381. foreach $f ( keys %him ) {
  382. printf "daemon dot file %s is size %d\n",
  383. $f, length $him{$f};
  384. }
  385. In our tied hash DotFiles example, we use a regular
  386. hash for the object containing several important
  387. fields, of which only the C<{LIST}> field will be what the
  388. user thinks of as the real hash.
  389. =over 5
  390. =item USER
  391. whose dot files this object represents
  392. =item HOME
  393. where those dot files live
  394. =item CLOBBER
  395. whether we should try to change or remove those dot files
  396. =item LIST
  397. the hash of dot file names and content mappings
  398. =back
  399. Here's the start of F<Dotfiles.pm>:
  400. package DotFiles;
  401. use Carp;
  402. sub whowasi { (caller(1))[3] . '()' }
  403. my $DEBUG = 0;
  404. sub debug { $DEBUG = @_ ? shift : 1 }
  405. For our example, we want to be able to emit debugging info to help in tracing
  406. during development. We keep also one convenience function around
  407. internally to help print out warnings; whowasi() returns the function name
  408. that calls it.
  409. Here are the methods for the DotFiles tied hash.
  410. =over 4
  411. =item TIEHASH classname, LIST
  412. This is the constructor for the class. That means it is expected to
  413. return a blessed reference through which the new object (probably but not
  414. necessarily an anonymous hash) will be accessed.
  415. Here's the constructor:
  416. sub TIEHASH {
  417. my $self = shift;
  418. my $user = shift || $>;
  419. my $dotdir = shift || '';
  420. croak "usage: @{[&whowasi]} [USER [DOTDIR]]" if @_;
  421. $user = getpwuid($user) if $user =~ /^\d+$/;
  422. my $dir = (getpwnam($user))[7]
  423. || croak "@{[&whowasi]}: no user $user";
  424. $dir .= "/$dotdir" if $dotdir;
  425. my $node = {
  426. USER => $user,
  427. HOME => $dir,
  428. LIST => {},
  429. CLOBBER => 0,
  430. };
  431. opendir(DIR, $dir)
  432. || croak "@{[&whowasi]}: can't opendir $dir: $!";
  433. foreach $dot ( grep /^\./ && -f "$dir/$_", readdir(DIR)) {
  434. $dot =~ s/^\.//;
  435. $node->{LIST}{$dot} = undef;
  436. }
  437. closedir DIR;
  438. return bless $node, $self;
  439. }
  440. It's probably worth mentioning that if you're going to filetest the
  441. return values out of a readdir, you'd better prepend the directory
  442. in question. Otherwise, because we didn't chdir() there, it would
  443. have been testing the wrong file.
  444. =item FETCH this, key
  445. This method will be triggered every time an element in the tied hash is
  446. accessed (read). It takes one argument beyond its self reference: the key
  447. whose value we're trying to fetch.
  448. Here's the fetch for our DotFiles example.
  449. sub FETCH {
  450. carp &whowasi if $DEBUG;
  451. my $self = shift;
  452. my $dot = shift;
  453. my $dir = $self->{HOME};
  454. my $file = "$dir/.$dot";
  455. unless (exists $self->{LIST}->{$dot} || -f $file) {
  456. carp "@{[&whowasi]}: no $dot file" if $DEBUG;
  457. return undef;
  458. }
  459. if (defined $self->{LIST}->{$dot}) {
  460. return $self->{LIST}->{$dot};
  461. } else {
  462. return $self->{LIST}->{$dot} = `cat $dir/.$dot`;
  463. }
  464. }
  465. It was easy to write by having it call the Unix cat(1) command, but it
  466. would probably be more portable to open the file manually (and somewhat
  467. more efficient). Of course, because dot files are a Unixy concept, we're
  468. not that concerned.
  469. =item STORE this, key, value
  470. This method will be triggered every time an element in the tied hash is set
  471. (written). It takes two arguments beyond its self reference: the index at
  472. which we're trying to store something, and the value we're trying to put
  473. there.
  474. Here in our DotFiles example, we'll be careful not to let
  475. them try to overwrite the file unless they've called the clobber()
  476. method on the original object reference returned by tie().
  477. sub STORE {
  478. carp &whowasi if $DEBUG;
  479. my $self = shift;
  480. my $dot = shift;
  481. my $value = shift;
  482. my $file = $self->{HOME} . "/.$dot";
  483. my $user = $self->{USER};
  484. croak "@{[&whowasi]}: $file not clobberable"
  485. unless $self->{CLOBBER};
  486. open(F, "> $file") || croak "can't open $file: $!";
  487. print F $value;
  488. close(F);
  489. }
  490. If they wanted to clobber something, they might say:
  491. $ob = tie %daemon_dots, 'daemon';
  492. $ob->clobber(1);
  493. $daemon_dots{signature} = "A true daemon\n";
  494. Another way to lay hands on a reference to the underlying object is to
  495. use the tied() function, so they might alternately have set clobber
  496. using:
  497. tie %daemon_dots, 'daemon';
  498. tied(%daemon_dots)->clobber(1);
  499. The clobber method is simply:
  500. sub clobber {
  501. my $self = shift;
  502. $self->{CLOBBER} = @_ ? shift : 1;
  503. }
  504. =item DELETE this, key
  505. This method is triggered when we remove an element from the hash,
  506. typically by using the delete() function. Again, we'll
  507. be careful to check whether they really want to clobber files.
  508. sub DELETE {
  509. carp &whowasi if $DEBUG;
  510. my $self = shift;
  511. my $dot = shift;
  512. my $file = $self->{HOME} . "/.$dot";
  513. croak "@{[&whowasi]}: won't remove file $file"
  514. unless $self->{CLOBBER};
  515. delete $self->{LIST}->{$dot};
  516. my $success = unlink($file);
  517. carp "@{[&whowasi]}: can't unlink $file: $!" unless $success;
  518. $success;
  519. }
  520. The value returned by DELETE becomes the return value of the call
  521. to delete(). If you want to emulate the normal behavior of delete(),
  522. you should return whatever FETCH would have returned for this key.
  523. In this example, we have chosen instead to return a value which tells
  524. the caller whether the file was successfully deleted.
  525. =item CLEAR this
  526. This method is triggered when the whole hash is to be cleared, usually by
  527. assigning the empty list to it.
  528. In our example, that would remove all the user's dot files! It's such a
  529. dangerous thing that they'll have to set CLOBBER to something higher than
  530. 1 to make it happen.
  531. sub CLEAR {
  532. carp &whowasi if $DEBUG;
  533. my $self = shift;
  534. croak "@{[&whowasi]}: won't remove all dot files for $self->{USER}"
  535. unless $self->{CLOBBER} > 1;
  536. my $dot;
  537. foreach $dot ( keys %{$self->{LIST}}) {
  538. $self->DELETE($dot);
  539. }
  540. }
  541. =item EXISTS this, key
  542. This method is triggered when the user uses the exists() function
  543. on a particular hash. In our example, we'll look at the C<{LIST}>
  544. hash element for this:
  545. sub EXISTS {
  546. carp &whowasi if $DEBUG;
  547. my $self = shift;
  548. my $dot = shift;
  549. return exists $self->{LIST}->{$dot};
  550. }
  551. =item FIRSTKEY this
  552. This method will be triggered when the user is going
  553. to iterate through the hash, such as via a keys() or each()
  554. call.
  555. sub FIRSTKEY {
  556. carp &whowasi if $DEBUG;
  557. my $self = shift;
  558. my $a = keys %{$self->{LIST}}; # reset each() iterator
  559. each %{$self->{LIST}}
  560. }
  561. =item NEXTKEY this, lastkey
  562. This method gets triggered during a keys() or each() iteration. It has a
  563. second argument which is the last key that had been accessed. This is
  564. useful if you're carrying about ordering or calling the iterator from more
  565. than one sequence, or not really storing things in a hash anywhere.
  566. For our example, we're using a real hash so we'll do just the simple
  567. thing, but we'll have to go through the LIST field indirectly.
  568. sub NEXTKEY {
  569. carp &whowasi if $DEBUG;
  570. my $self = shift;
  571. return each %{ $self->{LIST} }
  572. }
  573. =item UNTIE this
  574. This is called when C<untie> occurs.
  575. =item DESTROY this
  576. This method is triggered when a tied hash is about to go out of
  577. scope. You don't really need it unless you're trying to add debugging
  578. or have auxiliary state to clean up. Here's a very simple function:
  579. sub DESTROY {
  580. carp &whowasi if $DEBUG;
  581. }
  582. =back
  583. Note that functions such as keys() and values() may return huge lists
  584. when used on large objects, like DBM files. You may prefer to use the
  585. each() function to iterate over such. Example:
  586. # print out history file offsets
  587. use NDBM_File;
  588. tie(%HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0);
  589. while (($key,$val) = each %HIST) {
  590. print $key, ' = ', unpack('L',$val), "\n";
  591. }
  592. untie(%HIST);
  593. =head2 Tying FileHandles
  594. This is partially implemented now.
  595. A class implementing a tied filehandle should define the following
  596. methods: TIEHANDLE, at least one of PRINT, PRINTF, WRITE, READLINE, GETC,
  597. READ, and possibly CLOSE, UNTIE and DESTROY. The class can also provide: BINMODE,
  598. OPEN, EOF, FILENO, SEEK, TELL - if the corresponding perl operators are
  599. used on the handle.
  600. It is especially useful when perl is embedded in some other program,
  601. where output to STDOUT and STDERR may have to be redirected in some
  602. special way. See nvi and the Apache module for examples.
  603. In our example we're going to create a shouting handle.
  604. package Shout;
  605. =over 4
  606. =item TIEHANDLE classname, LIST
  607. This is the constructor for the class. That means it is expected to
  608. return a blessed reference of some sort. The reference can be used to
  609. hold some internal information.
  610. sub TIEHANDLE { print "<shout>\n"; my $i; bless \$i, shift }
  611. =item WRITE this, LIST
  612. This method will be called when the handle is written to via the
  613. C<syswrite> function.
  614. sub WRITE {
  615. $r = shift;
  616. my($buf,$len,$offset) = @_;
  617. print "WRITE called, \$buf=$buf, \$len=$len, \$offset=$offset";
  618. }
  619. =item PRINT this, LIST
  620. This method will be triggered every time the tied handle is printed to
  621. with the C<print()> function.
  622. Beyond its self reference it also expects the list that was passed to
  623. the print function.
  624. sub PRINT { $r = shift; $$r++; print join($,,map(uc($_),@_)),$\ }
  625. =item PRINTF this, LIST
  626. This method will be triggered every time the tied handle is printed to
  627. with the C<printf()> function.
  628. Beyond its self reference it also expects the format and list that was
  629. passed to the printf function.
  630. sub PRINTF {
  631. shift;
  632. my $fmt = shift;
  633. print sprintf($fmt, @_)."\n";
  634. }
  635. =item READ this, LIST
  636. This method will be called when the handle is read from via the C<read>
  637. or C<sysread> functions.
  638. sub READ {
  639. my $self = shift;
  640. my $$bufref = \$_[0];
  641. my(undef,$len,$offset) = @_;
  642. print "READ called, \$buf=$bufref, \$len=$len, \$offset=$offset";
  643. # add to $$bufref, set $len to number of characters read
  644. $len;
  645. }
  646. =item READLINE this
  647. This method will be called when the handle is read from via <HANDLE>.
  648. The method should return undef when there is no more data.
  649. sub READLINE { $r = shift; "READLINE called $$r times\n"; }
  650. =item GETC this
  651. This method will be called when the C<getc> function is called.
  652. sub GETC { print "Don't GETC, Get Perl"; return "a"; }
  653. =item CLOSE this
  654. This method will be called when the handle is closed via the C<close>
  655. function.
  656. sub CLOSE { print "CLOSE called.\n" }
  657. =item UNTIE this
  658. As with the other types of ties, this method will be called when C<untie> happens.
  659. It may be appropriate to "auto CLOSE" when this occurs.
  660. =item DESTROY this
  661. As with the other types of ties, this method will be called when the
  662. tied handle is about to be destroyed. This is useful for debugging and
  663. possibly cleaning up.
  664. sub DESTROY { print "</shout>\n" }
  665. =back
  666. Here's how to use our little example:
  667. tie(*FOO,'Shout');
  668. print FOO "hello\n";
  669. $a = 4; $b = 6;
  670. print FOO $a, " plus ", $b, " equals ", $a + $b, "\n";
  671. print <FOO>;
  672. =head2 UNTIE this
  673. You can define for all tie types an UNTIE method that will be called
  674. at untie().
  675. =head2 The C<untie> Gotcha
  676. If you intend making use of the object returned from either tie() or
  677. tied(), and if the tie's target class defines a destructor, there is a
  678. subtle gotcha you I<must> guard against.
  679. As setup, consider this (admittedly rather contrived) example of a
  680. tie; all it does is use a file to keep a log of the values assigned to
  681. a scalar.
  682. package Remember;
  683. use strict;
  684. use warnings;
  685. use IO::File;
  686. sub TIESCALAR {
  687. my $class = shift;
  688. my $filename = shift;
  689. my $handle = new IO::File "> $filename"
  690. or die "Cannot open $filename: $!\n";
  691. print $handle "The Start\n";
  692. bless {FH => $handle, Value => 0}, $class;
  693. }
  694. sub FETCH {
  695. my $self = shift;
  696. return $self->{Value};
  697. }
  698. sub STORE {
  699. my $self = shift;
  700. my $value = shift;
  701. my $handle = $self->{FH};
  702. print $handle "$value\n";
  703. $self->{Value} = $value;
  704. }
  705. sub DESTROY {
  706. my $self = shift;
  707. my $handle = $self->{FH};
  708. print $handle "The End\n";
  709. close $handle;
  710. }
  711. 1;
  712. Here is an example that makes use of this tie:
  713. use strict;
  714. use Remember;
  715. my $fred;
  716. tie $fred, 'Remember', 'myfile.txt';
  717. $fred = 1;
  718. $fred = 4;
  719. $fred = 5;
  720. untie $fred;
  721. system "cat myfile.txt";
  722. This is the output when it is executed:
  723. The Start
  724. 1
  725. 4
  726. 5
  727. The End
  728. So far so good. Those of you who have been paying attention will have
  729. spotted that the tied object hasn't been used so far. So lets add an
  730. extra method to the Remember class to allow comments to be included in
  731. the file -- say, something like this:
  732. sub comment {
  733. my $self = shift;
  734. my $text = shift;
  735. my $handle = $self->{FH};
  736. print $handle $text, "\n";
  737. }
  738. And here is the previous example modified to use the C<comment> method
  739. (which requires the tied object):
  740. use strict;
  741. use Remember;
  742. my ($fred, $x);
  743. $x = tie $fred, 'Remember', 'myfile.txt';
  744. $fred = 1;
  745. $fred = 4;
  746. comment $x "changing...";
  747. $fred = 5;
  748. untie $fred;
  749. system "cat myfile.txt";
  750. When this code is executed there is no output. Here's why:
  751. When a variable is tied, it is associated with the object which is the
  752. return value of the TIESCALAR, TIEARRAY, or TIEHASH function. This
  753. object normally has only one reference, namely, the implicit reference
  754. from the tied variable. When untie() is called, that reference is
  755. destroyed. Then, as in the first example above, the object's
  756. destructor (DESTROY) is called, which is normal for objects that have
  757. no more valid references; and thus the file is closed.
  758. In the second example, however, we have stored another reference to
  759. the tied object in $x. That means that when untie() gets called
  760. there will still be a valid reference to the object in existence, so
  761. the destructor is not called at that time, and thus the file is not
  762. closed. The reason there is no output is because the file buffers
  763. have not been flushed to disk.
  764. Now that you know what the problem is, what can you do to avoid it?
  765. Prior to the introduction of the optional UNTIE method the only way
  766. was the good old C<-w> flag. Which will spot any instances where you call
  767. untie() and there are still valid references to the tied object. If
  768. the second script above this near the top C<use warnings 'untie'>
  769. or was run with the C<-w> flag, Perl prints this
  770. warning message:
  771. untie attempted while 1 inner references still exist
  772. To get the script to work properly and silence the warning make sure
  773. there are no valid references to the tied object I<before> untie() is
  774. called:
  775. undef $x;
  776. untie $fred;
  777. Now that UNTIE exists the class designer can decide which parts of the
  778. class functionality are really associated with C<untie> and which with
  779. the object being destroyed. What makes sense for a given class depends
  780. on whether the inner references are being kept so that non-tie-related
  781. methods can be called on the object. But in most cases it probably makes
  782. sense to move the functionality that would have been in DESTROY to the UNTIE
  783. method.
  784. If the UNTIE method exists then the warning above does not occur. Instead the
  785. UNTIE method is passed the count of "extra" references and can issue its own
  786. warning if appropriate. e.g. to replicate the no UNTIE case this method can
  787. be used:
  788. sub UNTIE
  789. {
  790. my ($obj,$count) = @_;
  791. carp "untie attempted while $count inner references still exist" if $count;
  792. }
  793. =head1 SEE ALSO
  794. See L<DB_File> or L<Config> for some interesting tie() implementations.
  795. A good starting point for many tie() implementations is with one of the
  796. modules L<Tie::Scalar>, L<Tie::Array>, L<Tie::Hash>, or L<Tie::Handle>.
  797. =head1 BUGS
  798. You cannot easily tie a multilevel data structure (such as a hash of
  799. hashes) to a dbm file. The first problem is that all but GDBM and
  800. Berkeley DB have size limitations, but beyond that, you also have problems
  801. with how references are to be represented on disk. One experimental
  802. module that does attempt to address this need partially is the MLDBM
  803. module. Check your nearest CPAN site as described in L<perlmodlib> for
  804. source code to MLDBM.
  805. Tied filehandles are still incomplete. sysopen(), truncate(),
  806. flock(), fcntl(), stat() and -X can't currently be trapped.
  807. =head1 AUTHOR
  808. Tom Christiansen
  809. TIEHANDLE by Sven Verdoolaege <F<[email protected]>> and Doug MacEachern <F<[email protected]>>
  810. UNTIE by Nick Ing-Simmons <F<[email protected]>>
  811. Tying Arrays by Casey Tweten <F<[email protected]>>