Add built local::lib
[catagits/Gitalist.git] / local-lib5 / lib / perl5 / i486-linux-gnu-thread-multi / autobox.pod
1 =pod
2
3 =head1 NAME
4
5 autobox - call methods on native types
6
7 =head1 SYNOPSIS
8
9     use autobox;
10
11     # integers
12
13         my $range = 10->to(1); # [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ]
14
15     # floats
16
17         my $error = 3.1415927->minus(22/7)->abs();
18
19     # strings
20
21         my @list = 'SELECT * FROM foo'->list();
22         my $greeting = "Hello, world!"->upper(); # "HELLO, WORLD!"
23
24         $greeting->for_each(\&character_handler);
25
26     # arrays and array refs
27
28         my $schwartzian = @_->map(...)->sort(...)->map(...);
29         my $hash = [ 'SELECT * FROM foo WHERE id IN (?, ?)', 1, 2 ]->hash();
30
31     # hashes and hash refs
32
33         { alpha => 'beta', gamma => 'vlissides' }->for_each(...);
34         %hash->keys();
35
36     # code refs
37
38         my $plus_five = (\&add)->curry()->(5);
39         my $minus_three = sub { $_[0] - $_[1] }->reverse->curry->(3);
40
41     # can() and isa() work as expected
42
43         if ("Hello, world!"->can('foo')) ...
44         if (3.1415927->isa('SCALAR')) ...
45
46 =head1 DESCRIPTION
47
48 The autobox pragma allows methods to be called on integers, floats, strings, arrays,
49 hashes, and code references in exactly the same manner as blessed references.
50
51 The autoboxing is transparent: boxed values are not blessed into their (user-defined)
52 implementation class (unless the method elects to bestow such a blessing) - they simply
53 use its methods as though they are.
54
55 The classes (packages) into which the native types are boxed are fully configurable.
56 By default, a method invoked on a non-object is assumed to be
57 defined in a class whose name corresponds to the C<ref()> type of that
58 value - or SCALAR if the value is a non-reference.
59
60 This mapping can be overriden by passing key/value pairs to the C<use autobox>
61 statement, in which the keys represent native types, and the values
62 their associated classes.
63
64 As with regular objects, autoboxed values are passed as the first argument of the specified method.
65 Consequently, given a vanilla C<use autobox>:
66
67     "Hello, world!"->upper()
68
69 is invoked as:
70
71     SCALAR::upper("hello, world!")
72
73 while:
74
75     [ 1 .. 10 ]->for_each(sub { ... })
76
77 resolves to:
78
79     ARRAY::for_each([ 1 .. 10 ], sub { ... })
80
81 Values beginning with the array C<@> and hash C<%> sigils are passed by reference, i.e. under the default bindings:
82
83     @array->join(', ')
84     @{ ... }->length()
85     %hash->keys()
86     %$hash->values()
87
88 are equivalent to:
89
90     ARRAY::join(\@array, ', ')
91     ARRAY::length(\@{ ... })
92     HASH::keys(\%hash)
93     HASH::values(\%$hash)
94
95 Multiple C<use autobox> statements can appear in the same scope. These are merged both "horizontally" (i.e.
96 mutiple classes can be associated with a particular type) and "vertically" (i.e. multiple classes can be associated
97 with multiple types).
98
99 Thus:
100
101     use autobox SCALAR => 'Foo';
102     use autobox SCALAR => 'Bar';
103
104 - associates SCALAR types with a synthetic class whose C<@ISA> includes both C<Foo> and C<Bar> (in that order).
105
106 Likewise:
107
108     use autobox SCALAR => 'Foo';
109     use autobox SCALAR => 'Bar';
110     use autobox ARRAY  => 'Baz';
111
112 and
113
114     use autobox SCALAR => [ 'Foo', 'Bar' ];
115     use autobox ARRAY  => 'Baz';
116
117 - bind SCALAR types to the C<Foo> and C<Bar> classes and ARRAY types to C<Baz>.  
118
119 C<autobox> is lexically scoped, and bindings for an outer scope
120 can be extended or countermanded in a nested scope:
121
122     {
123         use autobox; # default bindings: autobox all native types
124         ...
125
126         {
127             # appends 'MyScalar' to the @ISA associated with SCALAR types
128             use autobox SCALAR => 'MyScalar';
129             ...
130         }
131
132         # back to the default (no MyScalar)
133         ...
134     }
135
136 Autoboxing can be turned off entirely by using the C<no> syntax:
137
138     {
139         use autobox;
140         ...
141         no autobox;
142         ...
143     }
144
145 - or can be selectively disabled by passing arguments to the C<no autobox> statement:
146
147     use autobox; # default bindings
148
149     no autobox qw(SCALAR);
150
151     []->foo(); # OK: ARRAY::foo([])
152
153     "Hello, world!"->bar(); # runtime error
154
155 Autoboxing is not performed for barewords i.e. 
156
157     my $foo = Foo->new();
158
159 and:
160
161     my $foo = new Foo;
162
163 behave as expected.
164
165 Methods are called on native types by means of the L<arrow operator|perlop/"The Arrow Operator">. As with
166 regular objects, the right hand side of the operator can either be a bare method name or a variable containing
167 a method name or subroutine reference. Thus the following are all valid:
168
169     sub method1 { ... }
170     my $method2 = 'some_method';
171     my $method3 = sub { ... };
172     my $method4 = \&some_method;
173
174     " ... "->method1();
175     [ ... ]->$method2();
176     { ... }->$method3();
177     sub { ... }->$method4();
178
179 A native type is only asociated with a class if the type => class mapping
180 is supplied in the C<use autobox> statement. Thus the following will not work:
181
182     use autobox SCALAR => 'MyScalar';
183
184     @array->some_array_method();
185
186 - as no class is specified for the ARRAY type. Note: the result of calling a method 
187 on a native type that is not associated with a class is the usual runtime error message:
188
189     Can't call method "some_array_method" on unblessed reference at ...
190
191 As a convenience, there is one exception to this rule. If C<use autobox> is invoked with no arguments
192 (ignoring the DEBUG option) the four main native types are associated with classes of the same name.
193
194 Thus:
195
196     use autobox;
197
198 - is equivalent to:
199
200     use autobox
201         SCALAR => 'SCALAR',
202         ARRAY  => 'ARRAY',
203         HASH   => 'HASH',
204         CODE   => 'CODE';
205
206 This facilitates one-liners and prototypes:
207
208     use autobox;
209
210     sub SCALAR::split { [ split '', $_[0] ] }
211     sub ARRAY::length { scalar @{$_[0]} }
212
213     print "Hello, world!"->split->length();
214
215 However, using these default bindings is not recommended as there's no guarantee that another 
216 piece of code won't trample over the same namespace/methods.
217
218 =head1 OPTIONS
219
220 A mapping from native types to their user-defined classes can be specified
221 by passing a list of key/value pairs to the C<use autobox> statement.
222
223 The following example shows the range of valid arguments:
224
225     use autobox
226         SCALAR    => 'MyScalar'                     # class name
227         ARRAY     => 'MyNamespace::',               # class prefix (ending in '::')
228         HASH      => [ 'MyHash', 'MyNamespace::' ], # one or more class names and/or prefixes
229         CODE      => ...,                           # any of the 3 value types above
230         INTEGER   => ...,                           # any of the 3 value types above
231         FLOAT     => ...,                           # any of the 3 value types above
232         NUMBER    => ...,                           # any of the 3 value types above
233         STRING    => ...,                           # any of the 3 value types above
234         UNDEF     => ...,                           # any of the 3 value types above
235         UNIVERSAL => ...,                           # any of the 3 value types above
236         DEFAULT   => ...,                           # any of the 3 value types above
237         DEBUG     => ...;                           # boolean or coderef
238
239 The INTEGER, FLOAT, NUMBER, STRING, SCALAR, ARRAY, HASH, CODE, UNDEF, DEFAULT and UNIVERSAL options can take
240 three different types of value:
241
242 =over
243
244 =item *
245
246 A class name e.g.
247
248     use autobox INTEGER => 'MyInt';
249
250 This binds the specified native type to the specified class. All methods invoked on
251 literals or values of type C<key> will be dispatched as methods of the class specified in
252 the corresponding C<value>.
253
254 =item *
255
256 A namespace: this is a class prefix (up to and including the final '::')
257 to which the specified type name (INTEGER, FLOAT, STRING &c.) will be appended:
258
259 Thus:
260
261     use autobox ARRAY => 'Prelude::';
262
263 is equivalent to:
264
265     use autobox ARRAY => 'Prelude::ARRAY';
266
267 =item *
268
269 A reference to an array of class names and/or namespaces. This associates multiple classes with the
270 specified type.
271
272 =back
273
274 =head2 DEFAULT
275
276 The C<DEFAULT> option specifies bindings for any of the four default types (SCALAR, ARRAY, HASH and CODE)
277 not supplied in the C<use autobox> statement. As with the other options, the C<value> corresponding to
278 the C<DEFAULT> C<key> can be a class name, a namespace, or a reference to an array containing one or
279 more class names and/or namespaces.
280
281 Thus:
282
283     use autobox
284         STRING  => 'MyString',
285         DEFAULT => 'MyDefault';
286
287 is equivalent to:
288
289     use autobox
290         STRING  => 'MyString',
291         SCALAR  => 'MyDefault',
292         ARRAY   => 'MyDefault',
293         HASH    => 'MyDefault',
294         CODE    => 'MyDefault';
295
296 Which in turn is equivalent to:
297
298     use autobox
299         INTEGER => 'MyDefault',
300         FLOAT   => 'MyDefault',
301         STRING  => [ 'MyString', 'MyDefault' ],
302         ARRAY   => 'MyDefault',
303         HASH    => 'MyDefault',
304         CODE    => 'MyDefault';
305
306 Namespaces in DEFAULT values have the default type name appended, which, in the case of defaulted SCALAR types,
307 is SCALAR rather than INTEGER, FLOAT &c.
308
309 Thus:
310
311     use autobox
312         ARRAY   => 'MyArray',
313         HASH    => 'MyHash',
314         CODE    => 'MyCode',
315         DEFAULT => 'MyNamespace::';
316
317 is equivalent to:
318
319     use autobox
320         INTEGER => 'MyNamespace::SCALAR',
321         FLOAT   => 'MyNamespace::SCALAR',
322         STRING  => 'MyNamespace::SCALAR',
323         ARRAY   => 'MyArray',
324         HASH    => 'MyArray',
325         CODE    => 'MyCode';
326
327 Any of the four default types can be exempted from defaulting to the DEFAULT value by supplying a value of undef:
328
329     use autobox
330         HASH    => undef,
331         DEFAULT => 'MyDefault';
332
333     42->foo # ok: MyDefault::foo
334     []->bar # ok: MyDefault::bar
335
336     %INC->baz # not ok: runtime error
337
338 =head2 UNDEF
339
340 The pseudotype, UNDEF, can be used to autobox undefined values. These are not autoboxed by default.
341
342 This doesn't work:
343
344     use autobox;
345
346     undef->foo() # runtime error
347
348 This works:
349
350     use autobox UNDEF => 'MyUndef'; 
351
352     undef->foo(); # ok
353
354 So does this:
355
356     use autobox UNDEF => 'MyNamespace::'; 
357
358     undef->foo(); # ok
359
360 =head2 NUMBER, SCALAR and UNIVERSAL
361
362 The virtual types NUMBER, SCALAR and UNIVERSAL function as macros or shortcuts which create
363 bindings for their subtypes. The type hierarchy is as follows:
364
365   UNIVERSAL -+
366              |
367              +- SCALAR -+
368              |          |
369              |          +- NUMBER -+
370              |          |          |
371              |          |          +- INTEGER
372              |          |          |
373              |          |          +- FLOAT
374              |          |
375              |          +- STRING
376              |
377              +- ARRAY
378              |
379              +- HASH
380              |
381              +- CODE
382   
383 Thus:
384
385     use autobox NUMBER => 'MyNumber';
386
387 is equivalent to:
388
389     use autobox
390         INTEGER => 'MyNumber',
391         FLOAT   => 'MyNumber';
392
393 And:
394
395     use autobox SCALAR => 'MyScalar';
396
397 is equivalent to:
398
399     use autobox
400         INTEGER => 'MyScalar',
401         FLOAT   => 'MyScalar',
402         STRING  => 'MyScalar';
403
404 Virtual types can also be passed to C<unimport> via the C<no autobox> syntax. This disables autoboxing
405 for the corresponding subtypes e.g.
406
407     no autobox qw(NUMBER);
408
409 is equivalent to:
410
411     no autobox qw(INTEGER FLOAT);
412
413 Virtual type bindings can be mixed with ordinary bindings to provide fine-grained control over
414 inheritance and delegation. For instance:
415
416     use autobox
417         INTEGER => 'MyInteger',
418         NUMBER  => 'MyNumber',
419         SCALAR  => 'MyScalar';
420
421 would result in the following bindings:
422
423     42->foo             -> [ MyInteger, MyNumber, MyScalar ]
424     3.1415927->bar      -> [ MyNumber, MyScalar ]
425     "Hello, world!->baz -> [ MyScalar ]
426
427 Note that DEFAULT bindings take precedence over virtual type bindings i.e.
428
429     use autobox
430         UNIVERSAL => 'MyUniversal',
431         DEFAULT   => 'MyDefault'; # default SCALAR, ARRAY, HASH and CODE before UNIVERSAL
432
433 is equivalent to:
434
435   use autobox
436       INTEGER => [ 'MyDefault', 'MyUniversal' ],
437       FLOAT   => [ 'MyDefault', 'MyUniversal' ], # ... &c.
438
439 =head2 DEBUG
440
441 C<DEBUG> exposes the current bindings for the scope in which C<use autobox> is called by means
442 of a callback, or a static debugging function.
443
444 This allows the computed bindings to be seen in "longhand".
445
446 The option is ignored if the value corresponding to the C<DEBUG> key is false.
447
448 If the value is a CODE ref, then this sub is called with a reference to
449 the hash containing the computed bindings for the current scope.
450
451 Finally, if C<DEBUG> is true but not a CODE ref, the bindings are dumped
452 to STDERR.
453
454 Thus:
455
456     use autobox DEBUG => 1, ...
457
458 or
459
460     use autobox DEBUG => sub { ... }, ...
461
462 or
463
464     sub my_callback ($) {
465         my $hashref = shift;
466         ...
467     }
468
469     use autobox DEBUG => \&my_callback, ...
470
471 =head1 METHODS
472
473 =head2 import
474
475 On its own, C<autobox> doesn't implement any methods that can be called on native types.
476 However, its static method, C<import>, can be used to implement C<autobox> extensions i.e.
477 lexically scoped modules that provide C<autobox> bindings for one or more native types without requiring
478 calling code to C<use autobox>.
479
480 This is done by subclassing C<autobox> and overriding C<import>. This allows extensions to effectively
481 translate C<use MyModule> into a bespoke C<use autobox> call. e.g.:
482
483     package String::Trim;
484
485     use base qw(autobox);
486
487     sub import {
488         my $class = shift;
489         $class->SUPER::import(STRING => 'String::Trim::Scalar');
490     }
491
492     package String::Trim::Scalar;
493
494     sub trim {
495         my $string = shift;
496         $string =~ s/^\s+//;
497         $string =~ s/\s+$//;
498         $string;
499     }
500
501     1;
502
503 Note that C<trim> is defined in an auxilliary class rather than in C<String::Trim> itself to prevent
504 C<String::Trim>'s own methods (i.e. the methods it inherits from C<autobox>) being exposed to SCALAR types.
505
506 This module can now be used without a C<use autobox> statement to enable the C<trim> method in the current
507 lexical scope. e.g.:
508
509     #!/usr/bin/env perl
510
511     use String::Trim;
512
513     print "  Hello, world!  "->trim();
514
515 =head1 EXPORTS
516
517 Although C<autobox> doesn't export anything, it includes an additional module, C<autobox::universal>,
518 which exports a single subroutine, C<type>.
519
520 =head2 type
521
522 This sub returns the type of its argument within C<autobox> (which is essentially longhand for the type names
523 used within perl). This value is used by C<autobox> to associate a method invocant with its designated classes. e.g.
524
525     use autobox::universal qw(type);
526
527     type("Hello, world!") # STRING
528     type(42)              # INTEGER
529     type([ ])             # ARRAY
530     type(sub { })         # CODE
531
532 C<autobox::universal> is loaded automatically by C<autobox>, and, as its name suggests, can be used to install
533 a universal method (i.e. a method for all C<autobox> types) e.g. 
534
535     use autobox UNIVERSAL => 'autobox::universal';
536
537     42->type        # INTEGER
538     3.1415927->type # FLOAT
539     %ENV->type      # HASH
540     
541 =head1 CAVEATS
542
543 =head2 Performance
544
545 Autoboxing comes at a price. Calling
546
547     "Hello, world!"->length()
548
549 is slightly slower than the equivalent method call on a string-like object, and significantly slower than
550
551     length("Hello, world!")
552
553 =head2 Gotchas
554
555 =head3 Precedence
556
557 Due to Perl's precedence rules, some autoboxed literals may need to be parenthesized:
558
559 For instance, while this works:
560
561     my $curried = sub { ... }->curry();
562
563 this doesn't:
564
565     my $curried = \&foo->curry();
566
567 The solution is to wrap the reference in parentheses:
568
569     my $curried = (\&foo)->curry();
570
571 The same applies for signed integer and float literals:
572
573     # this works
574     my $range = 10->to(1);
575
576     # this doesn't work
577     my $range = -10->to(10);
578
579     # this works
580     my $range = (-10)->to(10);
581
582 =head3 print BLOCK
583
584 Perl's special-casing for the C<print BLOCK ...> syntax (see L<perlsub>) means that C<print { expression() } ...>
585 (where the curly brackets denote an anonymous HASH ref) may require some further disambiguation:
586
587     # this works (
588     print { foo => 'bar' }->foo();
589
590     # and this
591     print { 'foo', 'bar' }->foo();
592
593     # and even this
594     print { 'foo', 'bar', @_ }->foo();
595
596     # but this doesn't
597     print { @_ }->foo() ? 1 : 0 
598
599 In the latter case, the solution is to supply something
600 other than a HASH ref literal as the first argument
601 to C<print()>:
602
603     # e.g.
604     print STDOUT { @_ }->foo() ? 1 : 0;
605
606     # or
607     my $hashref = { @_ };
608     print $hashref->foo() ? 1 : 0; 
609
610     # or
611     print '', { @_ }->foo() ? 1 : 0; 
612
613     # or
614     print '' . { @_ }->foo() ? 1 : 0; 
615
616     # or even
617     { @_ }->print_if_foo(1, 0); 
618
619 =head3 VERSION, import and unimport
620
621 Although C<can> and C<isa> work as expected for autoboxed values, the C<VERSION> method doesn't.
622 Thus, while these work:
623
624     [ ... ]->can('pop')
625
626     3.1415->isa('MyScalar')
627
628 This doesn't:
629
630     use MyScalar 1.23;
631     use autobox SCALAR => 'MyScalar';
632
633     print "Hello, world!"->VERSION();
634
635 Though, of course:
636
637     print MyScalar->VERSION();
638
639 and
640         
641     print $MyScalar::VERSION;
642
643 continue to work.
644
645 Likewise, C<import> and C<unimport> are unaffected by the autobox pragma:
646
647     # equivalent to Foo->import() rather than MyScalar->import('Foo')
648     'Foo'->import()
649
650     # error: Can't call method "import" on unblessed reference
651     []->import()
652
653 =head3 eval EXPR
654
655 Like most pragmas autobox performs some of its operations at compile time, and,
656 as a result, runtime string C<eval>s are not executed within its scope i.e. this
657 doesn't work:
658
659     use autobox;
660
661     eval "42->foo";
662
663 The workaround is to use autobox within the C<eval> e.g.
664
665     eval <<'EOS';
666         use autobox;
667         42->foo(); 
668     EOS
669
670 Note that the C<eval BLOCK> form works as expected:
671
672     use autobox;
673     
674     eval { 42->foo() }; # OK
675         
676 =head1 VERSION
677
678 2.55
679
680 =head1 SEE ALSO
681
682 =over
683
684 =item * L<autobox::Closure::Attributes|autobox::Closure::Attributes>
685
686 =item * L<autobox::Core|autobox::Core>
687
688 =item * L<autobox::DateTime::Duration|autobox::DateTime::Duration>
689
690 =item * L<autobox::Encode|autobox::Encode>
691
692 =item * L<Moose::Autobox>
693
694 =item * L<Perl6::Contexts|Perl6::Contexts>
695
696 =item * L<Scalar::Properties|Scalar::Properties>
697
698 =item * L<Shell::Autobox|Shell::Autobox>
699
700 =back
701
702 =head1 AUTHOR
703     
704 chocolateboy <chocolate.boy@email.com>
705
706 =head1 COPYRIGHT
707
708 Copyright (c) 2003-2008, chocolateboy.
709
710 This module is free software. It may be used, redistributed
711 and/or modified under the same terms as Perl itself.
712
713 =cut