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, isa, VERSION, import and unimport can be accessed via autobox_class
42
43 42->autobox_class->isa('MyNumber')
44 say []->autobox_class->VERSION
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 Autoboxing is transparent: values are not blessed into their (user-
52 defined) implementation class (unless the method elects to bestow such
53 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 value is
57 assumed to be defined in a class whose name corresponds to the "ref()"
58 type of that value - or SCALAR if the value is a non-reference.
59
60 This mapping can be overridden 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. multiple classes can be
99 associated with a particular type) and "vertically" (i.e. multiple
100 classes can be 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 Baz.
122
123 autobox is lexically scoped, and bindings for an outer scope can be
124 extended or countermanded in a nested scope:
125
126 {
127 use autobox; # default bindings: autobox all native types
128 ...
129
130 {
131 # appends 'MyScalar' to the @ISA associated with SCALAR types
132 use autobox SCALAR => 'MyScalar';
133 ...
134 }
135
136 # back to the default (no MyScalar)
137 ...
138 }
139
140 Autoboxing can be turned off entirely by using the "no" syntax:
141
142 {
143 use autobox;
144 ...
145 no autobox;
146 ...
147 }
148
149 - or can be selectively disabled by passing arguments to the "no
150 autobox" statement:
151
152 use autobox; # default bindings
153
154 no autobox qw(SCALAR);
155
156 []->foo(); # OK: ARRAY::foo([])
157
158 "Hello, world!"->bar(); # runtime error
159
160 Autoboxing is not performed for barewords i.e.
161
162 my $foo = Foo->new();
163
164 and:
165
166 my $foo = new Foo;
167
168 behave as expected.
169
170 Methods are called on native types by means of the arrow operator. As
171 with regular objects, the right hand side of the operator can either be
172 a bare method name or a variable containing a method name or subroutine
173 reference. Thus the following are all valid:
174
175 sub method1 { ... }
176 my $method2 = 'some_method';
177 my $method3 = sub { ... };
178 my $method4 = \&some_method;
179
180 " ... "->method1();
181 [ ... ]->$method2();
182 { ... }->$method3();
183 sub { ... }->$method4();
184
185 A native type is only associated with a class if the type => class
186 mapping is supplied in the "use autobox" statement. Thus the following
187 will not work:
188
189 use autobox SCALAR => 'MyScalar';
190
191 @array->some_array_method();
192
193 - as no class is specified for the ARRAY type. Note: the result of
194 calling a method on a native type that is not associated with a class
195 is the usual runtime error message:
196
197 Can't call method "some_array_method" on unblessed reference at ...
198
199 As a convenience, there is one exception to this rule. If "use autobox"
200 is invoked with no arguments (ignoring the DEBUG option) the four main
201 native types are associated with classes of the same name.
202
203 Thus:
204
205 use autobox;
206
207 - is equivalent to:
208
209 use autobox {
210 SCALAR => 'SCALAR',
211 ARRAY => 'ARRAY',
212 HASH => 'HASH',
213 CODE => 'CODE',
214 }
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 hashref or a list of key/value pairs to the "use
232 autobox" 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
251 The INTEGER, FLOAT, NUMBER, STRING, SCALAR, ARRAY, HASH, CODE, UNDEF,
252 DEFAULT and UNIVERSAL options can take three different types of value:
253
254 · A class name e.g.
255
256 use autobox INTEGER => 'MyInt';
257
258 This binds the specified native type to the specified class. All
259 methods invoked on values of type "key" will be dispatched as
260 methods of the class specified in the corresponding "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
291 is equivalent to:
292
293 use autobox {
294 STRING => 'MyString',
295 SCALAR => 'MyDefault',
296 ARRAY => 'MyDefault',
297 HASH => 'MyDefault',
298 CODE => 'MyDefault',
299 }
300
301 Which in turn is equivalent to:
302
303 use autobox {
304 INTEGER => 'MyDefault',
305 FLOAT => 'MyDefault',
306 STRING => [ 'MyString', 'MyDefault' ],
307 ARRAY => 'MyDefault',
308 HASH => 'MyDefault',
309 CODE => 'MyDefault',
310 }
311
312 Namespaces in DEFAULT values have the default type name appended,
313 which, in the case of defaulted SCALAR types, is SCALAR rather than
314 INTEGER, FLOAT &c.
315
316 Thus:
317
318 use autobox {
319 ARRAY => 'MyArray',
320 HASH => 'MyHash',
321 CODE => 'MyCode',
322 DEFAULT => 'MyNamespace::',
323 }
324
325 is equivalent to:
326
327 use autobox {
328 INTEGER => 'MyNamespace::SCALAR',
329 FLOAT => 'MyNamespace::SCALAR',
330 STRING => 'MyNamespace::SCALAR',
331 ARRAY => 'MyArray',
332 HASH => 'MyArray',
333 CODE => 'MyCode',
334 }
335
336 Any of the four default types can be exempted from defaulting to the
337 DEFAULT value by supplying a value of undef:
338
339 use autobox {
340 HASH => undef,
341 DEFAULT => 'MyDefault',
342 }
343
344 42->foo # ok: MyDefault::foo
345 []->bar # ok: MyDefault::bar
346
347 %INC->baz # not ok: runtime error
348
349 UNDEF
350 The pseudotype, UNDEF, can be used to autobox undefined values. These
351 are not autoboxed by default.
352
353 This doesn't work:
354
355 use autobox;
356
357 undef->foo() # runtime error
358
359 This works:
360
361 use autobox UNDEF => 'MyUndef';
362
363 undef->foo(); # ok
364
365 So does this:
366
367 use autobox UNDEF => 'MyNamespace::';
368
369 undef->foo(); # ok
370
371 NUMBER, SCALAR and UNIVERSAL
372 The virtual types NUMBER, SCALAR and UNIVERSAL function as macros or
373 shortcuts which create bindings for their subtypes. The type hierarchy
374 is as follows:
375
376 UNIVERSAL -+
377 |
378 +- SCALAR -+
379 | |
380 | +- NUMBER -+
381 | | |
382 | | +- INTEGER
383 | | |
384 | | +- FLOAT
385 | |
386 | +- STRING
387 |
388 +- ARRAY
389 |
390 +- HASH
391 |
392 +- CODE
393
394 Thus:
395
396 use autobox NUMBER => 'MyNumber';
397
398 is equivalent to:
399
400 use autobox {
401 INTEGER => 'MyNumber',
402 FLOAT => 'MyNumber',
403 }
404
405 And:
406
407 use autobox SCALAR => 'MyScalar';
408
409 is equivalent to:
410
411 use autobox {
412 INTEGER => 'MyScalar',
413 FLOAT => 'MyScalar',
414 STRING => 'MyScalar',
415 }
416
417 Virtual types can also be passed to "unimport" via the "no autobox"
418 syntax. This disables autoboxing for the corresponding subtypes e.g.
419
420 no autobox qw(NUMBER);
421
422 is equivalent to:
423
424 no autobox qw(INTEGER FLOAT);
425
426 Virtual type bindings can be mixed with ordinary bindings to provide
427 fine-grained control over inheritance and delegation. For instance:
428
429 use autobox {
430 INTEGER => 'MyInteger',
431 NUMBER => 'MyNumber',
432 SCALAR => 'MyScalar',
433 }
434
435 would result in the following bindings:
436
437 42->foo -> [ MyInteger, MyNumber, MyScalar ]
438 3.1415927->bar -> [ MyNumber, MyScalar ]
439 "Hello, world!"->baz -> [ MyScalar ]
440
441 Note that DEFAULT bindings take precedence over virtual type bindings
442 i.e.
443
444 use autobox {
445 UNIVERSAL => 'MyUniversal',
446 DEFAULT => 'MyDefault', # default SCALAR, ARRAY, HASH and CODE before UNIVERSAL
447 }
448
449 is equivalent to:
450
451 use autobox {
452 INTEGER => [ 'MyDefault', 'MyUniversal' ],
453 FLOAT => [ 'MyDefault', 'MyUniversal' ], # ... &c.
454 }
455
456 DEBUG
457 "DEBUG" allows the autobox bindings for the current scope to be
458 inspected, either by dumping them to the console or passing them to a
459 callback function. This allows the computed bindings to be seen in
460 "longhand".
461
462 The option is ignored if the value corresponding to the "DEBUG" key is
463 false.
464
465 If the value is a CODE ref, it is called with a reference to the hash
466 containing the computed bindings for the current scope.
467
468 Finally, if "DEBUG" is true but not a CODE ref, the bindings are dumped
469 to STDERR.
470
471 Thus:
472
473 use autobox DEBUG => 1, ...
474
475 or
476
477 use autobox DEBUG => sub { ... }, ...
478
479 or
480
481 sub my_callback ($) {
482 my $hashref = shift;
483 ...
484 }
485
486 use autobox DEBUG => \&my_callback, ...
487
489 import
490 This method sets up autobox bindings for the current lexical scope. It
491 can be used to implement autobox extensions i.e. lexically-scoped
492 modules that provide autobox bindings for one or more native types
493 without requiring calling code to "use autobox".
494
495 This is done by subclassing autobox and overriding "import". This
496 allows extensions to effectively translate "use MyModule" into a
497 bespoke "use autobox" call e.g.:
498
499 package String::Trim;
500
501 use base qw(autobox);
502
503 sub import {
504 my $class = shift;
505
506 $class->SUPER::import(
507 STRING => 'String::Trim::String'
508 );
509 }
510
511 package String::Trim::String;
512
513 sub trim {
514 my $string = shift;
515 $string =~ s/^\s+//;
516 $string =~ s/\s+$//;
517 $string;
518 }
519
520 1;
521
522 Note that "trim" is defined in an auxiliary class rather than in
523 String::Trim itself to prevent String::Trim's own methods (i.e. the
524 methods it inherits from autobox) being exposed to "STRING" types.
525
526 This module can now be used without a "use autobox" statement to enable
527 the "trim" method in the current lexical scope e.g.:
528
529 #!/usr/bin/env perl
530
531 use String::Trim;
532
533 print " Hello, world! "->trim();
534
536 autobox_class
537 autobox adds a single method to all autoboxed types: "autobox_class".
538 This can be used to call UNIVERSAL methods i.e. "can", "DOES",
539 "import", "isa", "unimport" and "VERSION" e.g.
540
541 if (sub { ... }->autobox_class->can('curry')) ...
542 if (42->autobox_class->isa('SCALAR')) ...
543
544 Note: "autobox_class" must always be used when calling these methods.
545 Calling them directly on native types produces the same results as
546 calling them with autobox disabled e.g.:
547
548 42->isa('NUMBER') # "" (interpeted as "42"->isa("NUMBER"))
549 []->can('push') # Error: Can't call method "can" on unblessed reference
550
552 type
553 autobox includes an additional module, autobox::universal, which
554 exports a single subroutine, "type".
555
556 This sub returns the type of its argument within autobox (which is
557 essentially longhand for the type names used within perl). This value
558 is used by autobox to associate a method invocant with its designated
559 classes e.g.
560
561 use autobox::universal qw(type);
562
563 type("42") # STRING
564 type(42) # INTEGER
565 type(42.0) # FLOAT
566 type(undef) # UNDEF
567
568 autobox::universal is loaded automatically by autobox, and, as its name
569 suggests, can be used to install a universal "type" method for
570 autoboxed values e.g.
571
572 use autobox UNIVERSAL => 'autobox::universal';
573
574 42->type # INTEGER
575 3.1415927->type # FLOAT
576 %ENV->type # HASH
577
579 Performance
580 Calling
581
582 "Hello, world!"->length()
583
584 is slightly slower than the equivalent method call on a string-like
585 object, and significantly slower than
586
587 length("Hello, world!")
588
589 Gotchas
590 Precedence
591
592 Due to Perl's precedence rules, some autoboxed literals may need to be
593 parenthesized:
594
595 For instance, while this works:
596
597 my $curried = sub { ... }->curry();
598
599 this doesn't:
600
601 my $curried = \&foo->curry();
602
603 The solution is to wrap the reference in parentheses:
604
605 my $curried = (\&foo)->curry();
606
607 The same applies for signed integer and float literals:
608
609 # this works
610 my $range = 10->to(1);
611
612 # this doesn't work
613 my $range = -10->to(10);
614
615 # this works
616 my $range = (-10)->to(10);
617
618 print BLOCK
619
620 Perl's special-casing for the "print BLOCK ..." syntax (see perlsub)
621 means that "print { expression() } ..." (where the curly brackets
622 denote an anonymous HASH ref) may require some further disambiguation:
623
624 # this works
625 print { foo => 'bar' }->foo();
626
627 # and this
628 print { 'foo', 'bar' }->foo();
629
630 # and even this
631 print { 'foo', 'bar', @_ }->foo();
632
633 # but this doesn't
634 print { @_ }->foo() ? 1 : 0
635
636 In the latter case, the solution is to supply something other than a
637 HASH ref literal as the first argument to "print()":
638
639 # e.g.
640 print STDOUT { @_ }->foo() ? 1 : 0;
641
642 # or
643 my $hashref = { @_ };
644 print $hashref->foo() ? 1 : 0;
645
646 # or
647 print '', { @_ }->foo() ? 1 : 0;
648
649 # or
650 print '' . { @_ }->foo() ? 1 : 0;
651
652 # or even
653 { @_ }->print_if_foo(1, 0);
654
655 eval EXPR
656
657 Like most pragmas, autobox performs operations at compile time, and, as
658 a result, runtime string "eval"s are not executed within its scope i.e.
659 this doesn't work:
660
661 use autobox;
662
663 eval "42->foo";
664
665 The workaround is to use autobox within the "eval" e.g.
666
667 eval <<'EOS';
668 use autobox;
669 42->foo();
670 EOS
671
672 Note that the "eval BLOCK" form works as expected:
673
674 use autobox;
675
676 eval { 42->foo() }; # OK
677
678 Operator Overloading
679
680 Operator overloading via the overload pragma doesn't (automatically)
681 work. autobox works by lexically overriding the arrow operator. It
682 doesn't bless native types into objects, so overloading - or any other
683 kind of "magic" which depends on values being blessed - doesn't apply.
684
686 3.0.1
687
689 · autobox::Core
690
691 · Moose::Autobox
692
693 · perl5i
694
695 · Scalar::Properties
696
698 chocolateboy <chocolate@cpan.org>
699
701 Copyright (c) 2003-2018 by chocolateboy.
702
703 This library is free software; you can redistribute it and/or modify it
704 under the terms of the Artistic License 2.0
705 <http://www.opensource.org/licenses/artistic-license-2.0.php>.
706
707
708
709perl v5.28.1 2018-05-05 autobox(3)