Add the original source packages to maemo, source lenny
[dh-make-perl] / dev / i386 / libio-stringy-perl / io-stringy-2.110 / lib / IO / WrapTie.pm
1 # SEE DOCUMENTATION AT BOTTOM OF FILE
2
3
4 #------------------------------------------------------------
5 package IO::WrapTie;
6 #------------------------------------------------------------
7 require 5.004;              ### for tie
8 use strict;
9 use vars qw(@ISA @EXPORT $VERSION);
10 use Exporter;
11
12 # Inheritance, exporting, and package version:
13 @ISA     = qw(Exporter);
14 @EXPORT  = qw(wraptie);
15 $VERSION = "2.110";
16
17 # Function, exported.
18 sub wraptie {
19     IO::WrapTie::Master->new(@_);
20 }
21
22 # Class method; BACKWARDS-COMPATIBILITY ONLY!
23 sub new { 
24     shift; 
25     IO::WrapTie::Master->new(@_);
26 }
27
28
29
30 #------------------------------------------------------------
31 package IO::WrapTie::Master;
32 #------------------------------------------------------------
33
34 use strict;
35 use vars qw(@ISA $AUTOLOAD);
36 use IO::Handle;
37
38 # We inherit from IO::Handle to get methods which invoke i/o operators,
39 # like print(), on our tied handle:
40 @ISA = qw(IO::Handle);
41
42 #------------------------------
43 # new SLAVE, TIEARGS...
44 #------------------------------
45 # Create a new subclass of IO::Handle which...
46 #
47 #   (1) Handles i/o OPERATORS because it is tied to an instance of 
48 #       an i/o-like class, like IO::Scalar.
49 #
50 #   (2) Handles i/o METHODS by delegating them to that same tied object!.
51 #
52 # Arguments are the slave class (e.g., IO::Scalar), followed by all 
53 # the arguments normally sent into that class's TIEHANDLE method.
54 # In other words, much like the arguments to tie().  :-)
55 #
56 # NOTE:
57 # The thing $x we return must be a BLESSED REF, for ($x->print()).
58 # The underlying symbol must be a FILEHANDLE, for (print $x "foo").
59 # It has to have a way of getting to the "real" back-end object...
60 #
61 sub new {
62     my $master = shift;
63     my $io = IO::Handle->new;   ### create a new handle
64     my $slave = shift;
65     tie *$io, $slave, @_;       ### tie: will invoke slave's TIEHANDLE
66     bless $io, $master;         ### return a master
67 }
68
69 #------------------------------
70 # AUTOLOAD
71 #------------------------------
72 # Delegate method invocations on the master to the underlying slave.
73 #
74 sub AUTOLOAD {
75     my $method = $AUTOLOAD;
76     $method =~ s/.*:://;
77     my $self = shift; tied(*$self)->$method(\@_);
78 }
79
80 #------------------------------
81 # PRELOAD
82 #------------------------------
83 # Utility.
84 #
85 # Most methods like print(), getline(), etc. which work on the tied object 
86 # via Perl's i/o operators (like 'print') are inherited from IO::Handle.
87 #
88 # Other methods, like seek() and sref(), we must delegate ourselves.
89 # AUTOLOAD takes care of these.
90 #
91 # However, it may be necessary to preload delegators into your
92 # own class.  PRELOAD will do this.
93 #
94 sub PRELOAD {
95     my $class = shift;
96     foreach (@_) {
97         eval "sub ${class}::$_ { my \$s = shift; tied(*\$s)->$_(\@_) }";
98     }    
99 }
100
101 # Preload delegators for some standard methods which we can't simply
102 # inherit from IO::Handle... for example, some IO::Handle methods 
103 # assume that there is an underlying file descriptor.
104 #
105 PRELOAD IO::WrapTie::Master 
106     qw(open opened close read clearerr eof seek tell setpos getpos);
107
108
109
110 #------------------------------------------------------------
111 package IO::WrapTie::Slave;
112 #------------------------------------------------------------
113 # Teeny private class providing a new_tie constructor...
114 #
115 # HOW IT ALL WORKS:
116
117 # Slaves inherit from this class.
118 #
119 # When you send a new_tie() message to a tie-slave class (like IO::Scalar),
120 # it first determines what class should provide its master, via TIE_MASTER.
121 # In this case, IO::Scalar->TIE_MASTER would return IO::Scalar::Master.
122 # Then, we create a new master (an IO::Scalar::Master) with the same args
123 # sent to new_tie.
124 #
125 # In general, the new() method of the master is inherited directly 
126 # from IO::WrapTie::Master.
127 #
128 sub new_tie {
129     my $self = shift;
130     $self->TIE_MASTER->new($self,@_);     ### e.g., IO::Scalar::Master->new(@_)
131 }
132
133 # Default class method for new_tie().
134 # All your tie-slave class (like IO::Scalar) has to do is override this 
135 # method with a method that returns the name of an appropriate "master"
136 # class for tying that slave.
137 #
138 sub TIE_MASTER { 'IO::WrapTie::Master' }
139
140 #------------------------------
141 1;
142 __END__
143
144
145 package IO::WrapTie;      ### for doc generator
146
147
148 =head1 NAME
149
150 IO::WrapTie - wrap tieable objects in IO::Handle interface
151
152 I<This is currently Alpha code, released for comments.  
153   Please give me your feedback!>
154
155
156 =head1 SYNOPSIS
157
158 First of all, you'll need tie(), so:
159
160    require 5.004;
161
162 I<Function interface (experimental).>
163 Use this with any existing class...
164
165    use IO::WrapTie;
166    use FooHandle;                  ### implements TIEHANDLE interface
167
168    ### Suppose we want a "FooHandle->new(&FOO_RDWR, 2)".
169    ### We can instead say...
170
171    $FH = wraptie('FooHandle', &FOO_RDWR, 2); 
172
173    ### Now we can use...    
174    print $FH "Hello, ";            ### traditional operator syntax...
175    $FH->print("world!\n");         ### ...and OO syntax as well!
176
177 I<OO interface (preferred).>
178 You can inherit from the IO::WrapTie::Slave mixin to get a
179 nifty C<new_tie()> constructor...
180
181    #------------------------------    
182    package FooHandle;                        ### a class which can TIEHANDLE
183
184    use IO::WrapTie;  
185    @ISA = qw(IO::WrapTie::Slave);            ### inherit new_tie()
186    ...
187
188
189    #------------------------------    
190    package main; 
191
192    $FH = FooHandle->new_tie(&FOO_RDWR, 2);   ### $FH is an IO::WrapTie::Master
193    print $FH "Hello, ";                      ### traditional operator syntax
194    $FH->print("world!\n");                   ### OO syntax
195
196 See IO::Scalar as an example.  It also shows you how to create classes
197 which work both with and without 5.004.
198
199
200 =head1 DESCRIPTION
201
202 Suppose you have a class C<FooHandle>, where...
203
204 =over 4
205
206 =item *
207
208 B<FooHandle does not inherit from IO::Handle;> that is, it performs
209 filehandle-like I/O, but to something other than an underlying
210 file descriptor.  Good examples are IO::Scalar (for printing to a
211 string) and IO::Lines (for printing to an array of lines).
212
213 =item *
214
215 B<FooHandle implements the TIEHANDLE interface> (see L<perltie>);
216 that is, it provides methods TIEHANDLE, GETC, PRINT, PRINTF,
217 READ, and READLINE.
218
219 =item *
220
221 B<FooHandle implements the traditional OO interface> of
222 FileHandle and IO::Handle; i.e., it contains methods like getline(), 
223 read(), print(), seek(), tell(), eof(), etc.
224
225 =back
226
227
228 Normally, users of your class would have two options:
229
230
231 =over 4
232
233 =item *
234
235 B<Use only OO syntax,> and forsake named I/O operators like 'print'.
236
237 =item * 
238
239 B<Use with tie,> and forsake treating it as a first-class object 
240 (i.e., class-specific methods can only be invoked through the underlying
241 object via tied()... giving the object a "split personality").
242
243 =back
244
245
246 But now with IO::WrapTie, you can say:
247
248     $WT = wraptie('FooHandle', &FOO_RDWR, 2);
249     $WT->print("Hello, world\n");   ### OO syntax
250     print $WT "Yes!\n";             ### Named operator syntax too!
251     $WT->weird_stuff;               ### Other methods!
252
253 And if you're authoring a class like FooHandle, just have it inherit 
254 from C<IO::WrapTie::Slave> and that first line becomes even prettier:
255
256     $WT = FooHandle->new_tie(&FOO_RDWR, 2);
257
258 B<The bottom line:> now, almost any class can look and work exactly like
259 an IO::Handle... and be used both with OO and non-OO filehandle syntax.
260
261
262 =head1 HOW IT ALL WORKS
263
264
265 =head2 The data structures
266
267 Consider this example code, using classes in this distribution:
268
269     use IO::Scalar;
270     use IO::WrapTie;
271
272     $WT = wraptie('IO::Scalar',\$s);
273     print $WT "Hello, ";
274     $WT->print("world!\n");
275
276 In it, the wraptie() function creates a data structure as follows:
277
278                           * $WT is a blessed reference to a tied filehandle
279               $WT           glob; that glob is tied to the "Slave" object.
280                |          * You would do all your i/o with $WT directly.
281                |       
282                |
283                |     ,---isa--> IO::WrapTie::Master >--isa--> IO::Handle
284                V    /
285         .-------------. 
286         |             | 
287         |             |   * Perl i/o operators work on the tied object,  
288         |  "Master"   |     invoking the TIEHANDLE methods.
289         |             |   * Method invocations are delegated to the tied 
290         |             |     slave.
291         `-------------' 
292                |    
293     tied(*$WT) |     .---isa--> IO::WrapTie::Slave
294                V    /   
295         .-------------.
296         |             |
297         |   "Slave"   |   * Instance of FileHandle-like class which doesn't
298         |             |     actually use file descriptors, like IO::Scalar.
299         |  IO::Scalar |   * The slave can be any kind of object.
300         |             |   * Must implement the TIEHANDLE interface.
301         `-------------'
302
303
304 I<NOTE:> just as an IO::Handle is really just a blessed reference to a 
305 I<traditional> filehandle glob... so also, an IO::WrapTie::Master 
306 is really just a blessed reference to a filehandle 
307 glob I<which has been tied to some "slave" class.>
308
309
310 =head2 How wraptie() works
311
312 =over 4
313
314 =item 1.
315
316 The call to function C<wraptie(SLAVECLASS, TIEARGS...)> is 
317 passed onto C<IO::WrapTie::Master::new()>.  
318 Note that class IO::WrapTie::Master is a subclass of IO::Handle.
319
320 =item 2.
321
322 The C<IO::WrapTie::Master::new> method creates a new IO::Handle object,
323 reblessed into class IO::WrapTie::Master.  This object is the I<master>, 
324 which will be returned from the constructor.  At the same time...
325
326 =item 3.
327
328 The C<new> method also creates the I<slave>: this is an instance 
329 of SLAVECLASS which is created by tying the master's IO::Handle 
330 to SLAVECLASS via C<tie(HANDLE, SLAVECLASS, TIEARGS...)>.  
331 This call to C<tie()> creates the slave in the following manner:
332
333 =item 4.
334
335 Class SLAVECLASS is sent the message C<TIEHANDLE(TIEARGS...)>; it 
336 will usually delegate this to C<SLAVECLASS::new(TIEARGS...)>, resulting
337 in a new instance of SLAVECLASS being created and returned.
338
339 =item 5.
340
341 Once both master and slave have been created, the master is returned
342 to the caller.  
343
344 =back
345
346
347 =head2 How I/O operators work (on the master)
348
349 Consider using an i/o operator on the master:
350
351     print $WT "Hello, world!\n";   
352
353 Since the master ($WT) is really a [blessed] reference to a glob, 
354 the normal Perl i/o operators like C<print> may be used on it.
355 They will just operate on the symbol part of the glob.
356
357 Since the glob is tied to the slave, the slave's PRINT method 
358 (part of the TIEHANDLE interface) will be automatically invoked.  
359
360 If the slave is an IO::Scalar, that means IO::Scalar::PRINT will be 
361 invoked, and that method happens to delegate to the C<print()> method 
362 of the same class.  So the I<real> work is ultimately done by 
363 IO::Scalar::print().
364
365
366 =head2 How methods work (on the master)
367
368 Consider using a method on the master:
369
370     $WT->print("Hello, world!\n");
371
372 Since the master ($WT) is blessed into the class IO::WrapTie::Master,
373 Perl first attempts to find a C<print()> method there.  Failing that,
374 Perl next attempts to find a C<print()> method in the superclass,
375 IO::Handle.  It just so happens that there I<is> such a method;
376 that method merely invokes the C<print> i/o operator on the self object...
377 and for that, see above!
378
379 But let's suppose we're dealing with a method which I<isn't> part
380 of IO::Handle... for example:
381
382     my $sref = $WT->sref;
383
384 In this case, the intuitive behavior is to have the master delegate the
385 method invocation to the slave (now do you see where the designations
386 come from?).  This is indeed what happens: IO::WrapTie::Master contains
387 an AUTOLOAD method which performs the delegation.  
388
389 So: when C<sref()> can't be found in IO::Handle, the AUTOLOAD method
390 of IO::WrapTie::Master is invoked, and the standard behavior of
391 delegating the method to the underlying slave (here, an IO::Scalar)
392 is done.
393
394 Sometimes, to get this to work properly, you may need to create 
395 a subclass of IO::WrapTie::Master which is an effective master for
396 I<your> class, and do the delegation there.
397
398
399
400
401 =head1 NOTES
402
403 B<Why not simply use the object's OO interface?> 
404     Because that means forsaking the use of named operators
405 like print(), and you may need to pass the object to a subroutine
406 which will attempt to use those operators:
407
408     $O = FooHandle->new(&FOO_RDWR, 2);
409     $O->print("Hello, world\n");  ### OO syntax is okay, BUT....
410
411     sub nope { print $_[0] "Nope!\n" }
412  X  nope($O);                     ### ERROR!!! (not a glob ref)
413
414
415 B<Why not simply use tie()?> 
416     Because (1) you have to use tied() to invoke methods in the
417 object's public interface (yuck), and (2) you may need to pass 
418 the tied symbol to another subroutine which will attempt to treat 
419 it in an OO-way... and that will break it:
420
421     tie *T, 'FooHandle', &FOO_RDWR, 2; 
422     print T "Hello, world\n";   ### Operator is okay, BUT... 
423
424     tied(*T)->other_stuff;      ### yuck! AND...
425
426     sub nope { shift->print("Nope!\n") }
427  X  nope(\*T);                  ### ERROR!!! (method "print" on unblessed ref)
428
429
430 B<Why a master and slave? 
431   Why not simply write FooHandle to inherit from IO::Handle?>
432     I tried this, with an implementation similar to that of IO::Socket.  
433 The problem is that I<the whole point is to use this with objects
434 that don't have an underlying file/socket descriptor.>.
435 Subclassing IO::Handle will work fine for the OO stuff, and fine with 
436 named operators I<if> you tie()... but if you just attempt to say:
437
438     $IO = FooHandle->new(&FOO_RDWR, 2);
439     print $IO "Hello!\n";
440
441 you get a warning from Perl like:
442
443     Filehandle GEN001 never opened
444
445 because it's trying to do system-level i/o on an (unopened) file 
446 descriptor.  To avoid this, you apparently have to tie() the handle...
447 which brings us right back to where we started!  At least the
448 IO::WrapTie mixin lets us say:
449
450     $IO = FooHandle->new_tie(&FOO_RDWR, 2);
451     print $IO "Hello!\n";
452
453 and so is not I<too> bad.  C<:-)>
454
455
456 =head1 WARNINGS
457
458 Remember: this stuff is for doing FileHandle-like i/o on things
459 I<without underlying file descriptors>.  If you have an underlying
460 file descriptor, you're better off just inheriting from IO::Handle.
461
462 B<Be aware that new_tie() always returns an instance of a
463 kind of IO::WrapTie::Master...> it does B<not> return an instance 
464 of the i/o class you're tying to!  
465
466 Invoking some methods on the master object causes AUTOLOAD to delegate
467 them to the slave object... so it I<looks> like you're manipulating a 
468 "FooHandle" object directly, but you're not.
469
470 I have not explored all the ramifications of this use of tie().
471 I<Here there be dragons>.
472
473
474 =head1 VERSION
475
476 $Id: WrapTie.pm,v 1.2 2005/02/10 21:21:53 dfs Exp $
477
478
479 =head1 AUTHOR
480
481 =item Primary Maintainer
482
483 David F. Skoll (F<dfs@roaringpenguin.com>).
484
485 =item Original Author
486
487 Eryq (F<eryq@zeegee.com>).
488 President, ZeeGee Software Inc (F<http://www.zeegee.com>).
489
490 =cut
491