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