Source code of Windows XP (NT5)
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.

879 lines
27 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 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
  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 DESTROY this
  124. This method will be triggered when the tied variable needs to be destructed.
  125. As with other object classes, such a method is seldom necessary, because Perl
  126. deallocates its moribund object's memory for you automatically--this isn't
  127. C++, you know. We'll use a DESTROY method here for debugging purposes only.
  128. sub DESTROY {
  129. my $self = shift;
  130. confess "wrong type" unless ref $self;
  131. carp "[ Nice::DESTROY pid $$self ]" if $Nice::DEBUG;
  132. }
  133. =back
  134. That's about all there is to it. Actually, it's more than all there
  135. is to it, because we've done a few nice things here for the sake
  136. of completeness, robustness, and general aesthetics. Simpler
  137. TIESCALAR classes are certainly possible.
  138. =head2 Tying Arrays
  139. A class implementing a tied ordinary array should define the following
  140. methods: TIEARRAY, FETCH, STORE, FETCHSIZE, STORESIZE and perhaps DESTROY.
  141. FETCHSIZE and STORESIZE are used to provide C<$#array> and
  142. equivalent C<scalar(@array)> access.
  143. The methods POP, PUSH, SHIFT, UNSHIFT, SPLICE are required if the perl
  144. operator with the corresponding (but lowercase) name is to operate on the
  145. tied array. The B<Tie::Array> class can be used as a base class to implement
  146. these in terms of the basic five methods above.
  147. In addition EXTEND will be called when perl would have pre-extended
  148. allocation in a real array.
  149. This means that tied arrays are now I<complete>. The example below needs
  150. upgrading to illustrate this. (The documentation in B<Tie::Array> is more
  151. complete.)
  152. For this discussion, we'll implement an array whose indices are fixed at
  153. its creation. If you try to access anything beyond those bounds, you'll
  154. take an exception. For example:
  155. require Bounded_Array;
  156. tie @ary, 'Bounded_Array', 2;
  157. $| = 1;
  158. for $i (0 .. 10) {
  159. print "setting index $i: ";
  160. $ary[$i] = 10 * $i;
  161. $ary[$i] = 10 * $i;
  162. print "value of elt $i now $ary[$i]\n";
  163. }
  164. The preamble code for the class is as follows:
  165. package Bounded_Array;
  166. use Carp;
  167. use strict;
  168. =over
  169. =item TIEARRAY classname, LIST
  170. This is the constructor for the class. That means it is expected to
  171. return a blessed reference through which the new array (probably an
  172. anonymous ARRAY ref) will be accessed.
  173. In our example, just to show you that you don't I<really> have to return an
  174. ARRAY reference, we'll choose a HASH reference to represent our object.
  175. A HASH works out well as a generic record type: the C<{BOUND}> field will
  176. store the maximum bound allowed, and the C<{ARRAY}> field will hold the
  177. true ARRAY ref. If someone outside the class tries to dereference the
  178. object returned (doubtless thinking it an ARRAY ref), they'll blow up.
  179. This just goes to show you that you should respect an object's privacy.
  180. sub TIEARRAY {
  181. my $class = shift;
  182. my $bound = shift;
  183. confess "usage: tie(\@ary, 'Bounded_Array', max_subscript)"
  184. if @_ || $bound =~ /\D/;
  185. return bless {
  186. BOUND => $bound,
  187. ARRAY => [],
  188. }, $class;
  189. }
  190. =item FETCH this, index
  191. This method will be triggered every time an individual element the tied array
  192. is accessed (read). It takes one argument beyond its self reference: the
  193. index whose value we're trying to fetch.
  194. sub FETCH {
  195. my($self,$idx) = @_;
  196. if ($idx > $self->{BOUND}) {
  197. confess "Array OOB: $idx > $self->{BOUND}";
  198. }
  199. return $self->{ARRAY}[$idx];
  200. }
  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. For example:
  211. sub STORE {
  212. my($self, $idx, $value) = @_;
  213. print "[STORE $value at $idx]\n" if _debug;
  214. if ($idx > $self->{BOUND} ) {
  215. confess "Array OOB: $idx > $self->{BOUND}";
  216. }
  217. return $self->{ARRAY}[$idx] = $value;
  218. }
  219. =item DESTROY this
  220. This method will be triggered when the tied variable needs to be destructed.
  221. As with the scalar tie class, this is almost never needed in a
  222. language that does its own garbage collection, so this time we'll
  223. just leave it out.
  224. =back
  225. The code we presented at the top of the tied array class accesses many
  226. elements of the array, far more than we've set the bounds to. Therefore,
  227. it will blow up once they try to access beyond the 2nd element of @ary, as
  228. the following output demonstrates:
  229. setting index 0: value of elt 0 now 0
  230. setting index 1: value of elt 1 now 10
  231. setting index 2: value of elt 2 now 20
  232. setting index 3: Array OOB: 3 > 2 at Bounded_Array.pm line 39
  233. Bounded_Array::FETCH called at testba line 12
  234. =head2 Tying Hashes
  235. As the first Perl data type to be tied (see dbmopen()), hashes have the
  236. most complete and useful tie() implementation. A class implementing a
  237. tied hash should define the following methods: TIEHASH is the constructor.
  238. FETCH and STORE access the key and value pairs. EXISTS reports whether a
  239. key is present in the hash, and DELETE deletes one. CLEAR empties the
  240. hash by deleting all the key and value pairs. FIRSTKEY and NEXTKEY
  241. implement the keys() and each() functions to iterate over all the keys.
  242. And DESTROY is called when the tied variable is garbage collected.
  243. If this seems like a lot, then feel free to inherit from merely the
  244. standard Tie::Hash module for most of your methods, redefining only the
  245. interesting ones. See L<Tie::Hash> for details.
  246. Remember that Perl distinguishes between a key not existing in the hash,
  247. and the key existing in the hash but having a corresponding value of
  248. C<undef>. The two possibilities can be tested with the C<exists()> and
  249. C<defined()> functions.
  250. Here's an example of a somewhat interesting tied hash class: it gives you
  251. a hash representing a particular user's dot files. You index into the hash
  252. with the name of the file (minus the dot) and you get back that dot file's
  253. contents. For example:
  254. use DotFiles;
  255. tie %dot, 'DotFiles';
  256. if ( $dot{profile} =~ /MANPATH/ ||
  257. $dot{login} =~ /MANPATH/ ||
  258. $dot{cshrc} =~ /MANPATH/ )
  259. {
  260. print "you seem to set your MANPATH\n";
  261. }
  262. Or here's another sample of using our tied class:
  263. tie %him, 'DotFiles', 'daemon';
  264. foreach $f ( keys %him ) {
  265. printf "daemon dot file %s is size %d\n",
  266. $f, length $him{$f};
  267. }
  268. In our tied hash DotFiles example, we use a regular
  269. hash for the object containing several important
  270. fields, of which only the C<{LIST}> field will be what the
  271. user thinks of as the real hash.
  272. =over 5
  273. =item USER
  274. whose dot files this object represents
  275. =item HOME
  276. where those dot files live
  277. =item CLOBBER
  278. whether we should try to change or remove those dot files
  279. =item LIST
  280. the hash of dot file names and content mappings
  281. =back
  282. Here's the start of F<Dotfiles.pm>:
  283. package DotFiles;
  284. use Carp;
  285. sub whowasi { (caller(1))[3] . '()' }
  286. my $DEBUG = 0;
  287. sub debug { $DEBUG = @_ ? shift : 1 }
  288. For our example, we want to be able to emit debugging info to help in tracing
  289. during development. We keep also one convenience function around
  290. internally to help print out warnings; whowasi() returns the function name
  291. that calls it.
  292. Here are the methods for the DotFiles tied hash.
  293. =over
  294. =item TIEHASH classname, LIST
  295. This is the constructor for the class. That means it is expected to
  296. return a blessed reference through which the new object (probably but not
  297. necessarily an anonymous hash) will be accessed.
  298. Here's the constructor:
  299. sub TIEHASH {
  300. my $self = shift;
  301. my $user = shift || $>;
  302. my $dotdir = shift || '';
  303. croak "usage: @{[&whowasi]} [USER [DOTDIR]]" if @_;
  304. $user = getpwuid($user) if $user =~ /^\d+$/;
  305. my $dir = (getpwnam($user))[7]
  306. || croak "@{[&whowasi]}: no user $user";
  307. $dir .= "/$dotdir" if $dotdir;
  308. my $node = {
  309. USER => $user,
  310. HOME => $dir,
  311. LIST => {},
  312. CLOBBER => 0,
  313. };
  314. opendir(DIR, $dir)
  315. || croak "@{[&whowasi]}: can't opendir $dir: $!";
  316. foreach $dot ( grep /^\./ && -f "$dir/$_", readdir(DIR)) {
  317. $dot =~ s/^\.//;
  318. $node->{LIST}{$dot} = undef;
  319. }
  320. closedir DIR;
  321. return bless $node, $self;
  322. }
  323. It's probably worth mentioning that if you're going to filetest the
  324. return values out of a readdir, you'd better prepend the directory
  325. in question. Otherwise, because we didn't chdir() there, it would
  326. have been testing the wrong file.
  327. =item FETCH this, key
  328. This method will be triggered every time an element in the tied hash is
  329. accessed (read). It takes one argument beyond its self reference: the key
  330. whose value we're trying to fetch.
  331. Here's the fetch for our DotFiles example.
  332. sub FETCH {
  333. carp &whowasi if $DEBUG;
  334. my $self = shift;
  335. my $dot = shift;
  336. my $dir = $self->{HOME};
  337. my $file = "$dir/.$dot";
  338. unless (exists $self->{LIST}->{$dot} || -f $file) {
  339. carp "@{[&whowasi]}: no $dot file" if $DEBUG;
  340. return undef;
  341. }
  342. if (defined $self->{LIST}->{$dot}) {
  343. return $self->{LIST}->{$dot};
  344. } else {
  345. return $self->{LIST}->{$dot} = `cat $dir/.$dot`;
  346. }
  347. }
  348. It was easy to write by having it call the Unix cat(1) command, but it
  349. would probably be more portable to open the file manually (and somewhat
  350. more efficient). Of course, because dot files are a Unixy concept, we're
  351. not that concerned.
  352. =item STORE this, key, value
  353. This method will be triggered every time an element in the tied hash is set
  354. (written). It takes two arguments beyond its self reference: the index at
  355. which we're trying to store something, and the value we're trying to put
  356. there.
  357. Here in our DotFiles example, we'll be careful not to let
  358. them try to overwrite the file unless they've called the clobber()
  359. method on the original object reference returned by tie().
  360. sub STORE {
  361. carp &whowasi if $DEBUG;
  362. my $self = shift;
  363. my $dot = shift;
  364. my $value = shift;
  365. my $file = $self->{HOME} . "/.$dot";
  366. my $user = $self->{USER};
  367. croak "@{[&whowasi]}: $file not clobberable"
  368. unless $self->{CLOBBER};
  369. open(F, "> $file") || croak "can't open $file: $!";
  370. print F $value;
  371. close(F);
  372. }
  373. If they wanted to clobber something, they might say:
  374. $ob = tie %daemon_dots, 'daemon';
  375. $ob->clobber(1);
  376. $daemon_dots{signature} = "A true daemon\n";
  377. Another way to lay hands on a reference to the underlying object is to
  378. use the tied() function, so they might alternately have set clobber
  379. using:
  380. tie %daemon_dots, 'daemon';
  381. tied(%daemon_dots)->clobber(1);
  382. The clobber method is simply:
  383. sub clobber {
  384. my $self = shift;
  385. $self->{CLOBBER} = @_ ? shift : 1;
  386. }
  387. =item DELETE this, key
  388. This method is triggered when we remove an element from the hash,
  389. typically by using the delete() function. Again, we'll
  390. be careful to check whether they really want to clobber files.
  391. sub DELETE {
  392. carp &whowasi if $DEBUG;
  393. my $self = shift;
  394. my $dot = shift;
  395. my $file = $self->{HOME} . "/.$dot";
  396. croak "@{[&whowasi]}: won't remove file $file"
  397. unless $self->{CLOBBER};
  398. delete $self->{LIST}->{$dot};
  399. my $success = unlink($file);
  400. carp "@{[&whowasi]}: can't unlink $file: $!" unless $success;
  401. $success;
  402. }
  403. The value returned by DELETE becomes the return value of the call
  404. to delete(). If you want to emulate the normal behavior of delete(),
  405. you should return whatever FETCH would have returned for this key.
  406. In this example, we have chosen instead to return a value which tells
  407. the caller whether the file was successfully deleted.
  408. =item CLEAR this
  409. This method is triggered when the whole hash is to be cleared, usually by
  410. assigning the empty list to it.
  411. In our example, that would remove all the user's dot files! It's such a
  412. dangerous thing that they'll have to set CLOBBER to something higher than
  413. 1 to make it happen.
  414. sub CLEAR {
  415. carp &whowasi if $DEBUG;
  416. my $self = shift;
  417. croak "@{[&whowasi]}: won't remove all dot files for $self->{USER}"
  418. unless $self->{CLOBBER} > 1;
  419. my $dot;
  420. foreach $dot ( keys %{$self->{LIST}}) {
  421. $self->DELETE($dot);
  422. }
  423. }
  424. =item EXISTS this, key
  425. This method is triggered when the user uses the exists() function
  426. on a particular hash. In our example, we'll look at the C<{LIST}>
  427. hash element for this:
  428. sub EXISTS {
  429. carp &whowasi if $DEBUG;
  430. my $self = shift;
  431. my $dot = shift;
  432. return exists $self->{LIST}->{$dot};
  433. }
  434. =item FIRSTKEY this
  435. This method will be triggered when the user is going
  436. to iterate through the hash, such as via a keys() or each()
  437. call.
  438. sub FIRSTKEY {
  439. carp &whowasi if $DEBUG;
  440. my $self = shift;
  441. my $a = keys %{$self->{LIST}}; # reset each() iterator
  442. each %{$self->{LIST}}
  443. }
  444. =item NEXTKEY this, lastkey
  445. This method gets triggered during a keys() or each() iteration. It has a
  446. second argument which is the last key that had been accessed. This is
  447. useful if you're carrying about ordering or calling the iterator from more
  448. than one sequence, or not really storing things in a hash anywhere.
  449. For our example, we're using a real hash so we'll do just the simple
  450. thing, but we'll have to go through the LIST field indirectly.
  451. sub NEXTKEY {
  452. carp &whowasi if $DEBUG;
  453. my $self = shift;
  454. return each %{ $self->{LIST} }
  455. }
  456. =item DESTROY this
  457. This method is triggered when a tied hash is about to go out of
  458. scope. You don't really need it unless you're trying to add debugging
  459. or have auxiliary state to clean up. Here's a very simple function:
  460. sub DESTROY {
  461. carp &whowasi if $DEBUG;
  462. }
  463. =back
  464. Note that functions such as keys() and values() may return huge lists
  465. when used on large objects, like DBM files. You may prefer to use the
  466. each() function to iterate over such. Example:
  467. # print out history file offsets
  468. use NDBM_File;
  469. tie(%HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0);
  470. while (($key,$val) = each %HIST) {
  471. print $key, ' = ', unpack('L',$val), "\n";
  472. }
  473. untie(%HIST);
  474. =head2 Tying FileHandles
  475. This is partially implemented now.
  476. A class implementing a tied filehandle should define the following
  477. methods: TIEHANDLE, at least one of PRINT, PRINTF, WRITE, READLINE, GETC,
  478. READ, and possibly CLOSE and DESTROY.
  479. It is especially useful when perl is embedded in some other program,
  480. where output to STDOUT and STDERR may have to be redirected in some
  481. special way. See nvi and the Apache module for examples.
  482. In our example we're going to create a shouting handle.
  483. package Shout;
  484. =over
  485. =item TIEHANDLE classname, LIST
  486. This is the constructor for the class. That means it is expected to
  487. return a blessed reference of some sort. The reference can be used to
  488. hold some internal information.
  489. sub TIEHANDLE { print "<shout>\n"; my $i; bless \$i, shift }
  490. =item WRITE this, LIST
  491. This method will be called when the handle is written to via the
  492. C<syswrite> function.
  493. sub WRITE {
  494. $r = shift;
  495. my($buf,$len,$offset) = @_;
  496. print "WRITE called, \$buf=$buf, \$len=$len, \$offset=$offset";
  497. }
  498. =item PRINT this, LIST
  499. This method will be triggered every time the tied handle is printed to
  500. with the C<print()> function.
  501. Beyond its self reference it also expects the list that was passed to
  502. the print function.
  503. sub PRINT { $r = shift; $$r++; print join($,,map(uc($_),@_)),$\ }
  504. =item PRINTF this, LIST
  505. This method will be triggered every time the tied handle is printed to
  506. with the C<printf()> function.
  507. Beyond its self reference it also expects the format and list that was
  508. passed to the printf function.
  509. sub PRINTF {
  510. shift;
  511. my $fmt = shift;
  512. print sprintf($fmt, @_)."\n";
  513. }
  514. =item READ this, LIST
  515. This method will be called when the handle is read from via the C<read>
  516. or C<sysread> functions.
  517. sub READ {
  518. my $self = shift;
  519. my $$bufref = \$_[0];
  520. my(undef,$len,$offset) = @_;
  521. print "READ called, \$buf=$bufref, \$len=$len, \$offset=$offset";
  522. # add to $$bufref, set $len to number of characters read
  523. $len;
  524. }
  525. =item READLINE this
  526. This method will be called when the handle is read from via <HANDLE>.
  527. The method should return undef when there is no more data.
  528. sub READLINE { $r = shift; "READLINE called $$r times\n"; }
  529. =item GETC this
  530. This method will be called when the C<getc> function is called.
  531. sub GETC { print "Don't GETC, Get Perl"; return "a"; }
  532. =item CLOSE this
  533. This method will be called when the handle is closed via the C<close>
  534. function.
  535. sub CLOSE { print "CLOSE called.\n" }
  536. =item DESTROY this
  537. As with the other types of ties, this method will be called when the
  538. tied handle is about to be destroyed. This is useful for debugging and
  539. possibly cleaning up.
  540. sub DESTROY { print "</shout>\n" }
  541. =back
  542. Here's how to use our little example:
  543. tie(*FOO,'Shout');
  544. print FOO "hello\n";
  545. $a = 4; $b = 6;
  546. print FOO $a, " plus ", $b, " equals ", $a + $b, "\n";
  547. print <FOO>;
  548. =head2 The C<untie> Gotcha
  549. If you intend making use of the object returned from either tie() or
  550. tied(), and if the tie's target class defines a destructor, there is a
  551. subtle gotcha you I<must> guard against.
  552. As setup, consider this (admittedly rather contrived) example of a
  553. tie; all it does is use a file to keep a log of the values assigned to
  554. a scalar.
  555. package Remember;
  556. use strict;
  557. use IO::File;
  558. sub TIESCALAR {
  559. my $class = shift;
  560. my $filename = shift;
  561. my $handle = new IO::File "> $filename"
  562. or die "Cannot open $filename: $!\n";
  563. print $handle "The Start\n";
  564. bless {FH => $handle, Value => 0}, $class;
  565. }
  566. sub FETCH {
  567. my $self = shift;
  568. return $self->{Value};
  569. }
  570. sub STORE {
  571. my $self = shift;
  572. my $value = shift;
  573. my $handle = $self->{FH};
  574. print $handle "$value\n";
  575. $self->{Value} = $value;
  576. }
  577. sub DESTROY {
  578. my $self = shift;
  579. my $handle = $self->{FH};
  580. print $handle "The End\n";
  581. close $handle;
  582. }
  583. 1;
  584. Here is an example that makes use of this tie:
  585. use strict;
  586. use Remember;
  587. my $fred;
  588. tie $fred, 'Remember', 'myfile.txt';
  589. $fred = 1;
  590. $fred = 4;
  591. $fred = 5;
  592. untie $fred;
  593. system "cat myfile.txt";
  594. This is the output when it is executed:
  595. The Start
  596. 1
  597. 4
  598. 5
  599. The End
  600. So far so good. Those of you who have been paying attention will have
  601. spotted that the tied object hasn't been used so far. So lets add an
  602. extra method to the Remember class to allow comments to be included in
  603. the file -- say, something like this:
  604. sub comment {
  605. my $self = shift;
  606. my $text = shift;
  607. my $handle = $self->{FH};
  608. print $handle $text, "\n";
  609. }
  610. And here is the previous example modified to use the C<comment> method
  611. (which requires the tied object):
  612. use strict;
  613. use Remember;
  614. my ($fred, $x);
  615. $x = tie $fred, 'Remember', 'myfile.txt';
  616. $fred = 1;
  617. $fred = 4;
  618. comment $x "changing...";
  619. $fred = 5;
  620. untie $fred;
  621. system "cat myfile.txt";
  622. When this code is executed there is no output. Here's why:
  623. When a variable is tied, it is associated with the object which is the
  624. return value of the TIESCALAR, TIEARRAY, or TIEHASH function. This
  625. object normally has only one reference, namely, the implicit reference
  626. from the tied variable. When untie() is called, that reference is
  627. destroyed. Then, as in the first example above, the object's
  628. destructor (DESTROY) is called, which is normal for objects that have
  629. no more valid references; and thus the file is closed.
  630. In the second example, however, we have stored another reference to
  631. the tied object in C<$x>. That means that when untie() gets called
  632. there will still be a valid reference to the object in existence, so
  633. the destructor is not called at that time, and thus the file is not
  634. closed. The reason there is no output is because the file buffers
  635. have not been flushed to disk.
  636. Now that you know what the problem is, what can you do to avoid it?
  637. Well, the good old C<-w> flag will spot any instances where you call
  638. untie() and there are still valid references to the tied object. If
  639. the second script above is run with the C<-w> flag, Perl prints this
  640. warning message:
  641. untie attempted while 1 inner references still exist
  642. To get the script to work properly and silence the warning make sure
  643. there are no valid references to the tied object I<before> untie() is
  644. called:
  645. undef $x;
  646. untie $fred;
  647. =head1 SEE ALSO
  648. See L<DB_File> or L<Config> for some interesting tie() implementations.
  649. =head1 BUGS
  650. Tied arrays are I<incomplete>. They are also distinctly lacking something
  651. for the C<$#ARRAY> access (which is hard, as it's an lvalue), as well as
  652. the other obvious array functions, like push(), pop(), shift(), unshift(),
  653. and splice().
  654. You cannot easily tie a multilevel data structure (such as a hash of
  655. hashes) to a dbm file. The first problem is that all but GDBM and
  656. Berkeley DB have size limitations, but beyond that, you also have problems
  657. with how references are to be represented on disk. One experimental
  658. module that does attempt to address this need partially is the MLDBM
  659. module. Check your nearest CPAN site as described in L<perlmodlib> for
  660. source code to MLDBM.
  661. =head1 AUTHOR
  662. Tom Christiansen
  663. TIEHANDLE by Sven Verdoolaege <F<[email protected]>> and Doug MacEachern <F<[email protected]>>