5 autobox - call methods on native types
13 my $range = 10->to(1); # [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ]
17 my $error = 3.1415927->minus(22/7)->abs();
21 my @list = 'SELECT * FROM foo'->list();
22 my $greeting = "Hello, world!"->upper(); # "HELLO, WORLD!"
24 $greeting->for_each(\&character_handler);
26 # arrays and array refs
28 my $schwartzian = @_->map(...)->sort(...)->map(...);
29 my $hash = [ 'SELECT * FROM foo WHERE id IN (?, ?)', 1, 2 ]->hash();
31 # hashes and hash refs
33 { alpha => 'beta', gamma => 'vlissides' }->for_each(...);
38 my $plus_five = (\&add)->curry()->(5);
39 my $minus_three = sub { $_[0] - $_[1] }->reverse->curry->(3);
41 # can() and isa() work as expected
43 if ("Hello, world!"->can('foo')) ...
44 if (3.1415927->isa('SCALAR')) ...
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.
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.
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.
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.
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>:
67 "Hello, world!"->upper()
71 SCALAR::upper("hello, world!")
75 [ 1 .. 10 ]->for_each(sub { ... })
79 ARRAY::for_each([ 1 .. 10 ], sub { ... })
81 Values beginning with the array C<@> and hash C<%> sigils are passed by reference, i.e. under the default bindings:
90 ARRAY::join(\@array, ', ')
91 ARRAY::length(\@{ ... })
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
101 use autobox SCALAR => 'Foo';
102 use autobox SCALAR => 'Bar';
104 - associates SCALAR types with a synthetic class whose C<@ISA> includes both C<Foo> and C<Bar> (in that order).
108 use autobox SCALAR => 'Foo';
109 use autobox SCALAR => 'Bar';
110 use autobox ARRAY => 'Baz';
114 use autobox SCALAR => [ 'Foo', 'Bar' ];
115 use autobox ARRAY => 'Baz';
117 - bind SCALAR types to the C<Foo> and C<Bar> classes and ARRAY types to C<Baz>.
119 C<autobox> is lexically scoped, and bindings for an outer scope
120 can be extended or countermanded in a nested scope:
123 use autobox; # default bindings: autobox all native types
127 # appends 'MyScalar' to the @ISA associated with SCALAR types
128 use autobox SCALAR => 'MyScalar';
132 # back to the default (no MyScalar)
136 Autoboxing can be turned off entirely by using the C<no> syntax:
145 - or can be selectively disabled by passing arguments to the C<no autobox> statement:
147 use autobox; # default bindings
149 no autobox qw(SCALAR);
151 []->foo(); # OK: ARRAY::foo([])
153 "Hello, world!"->bar(); # runtime error
155 Autoboxing is not performed for barewords i.e.
157 my $foo = Foo->new();
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:
170 my $method2 = 'some_method';
171 my $method3 = sub { ... };
172 my $method4 = \&some_method;
177 sub { ... }->$method4();
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:
182 use autobox SCALAR => 'MyScalar';
184 @array->some_array_method();
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:
189 Can't call method "some_array_method" on unblessed reference at ...
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.
206 This facilitates one-liners and prototypes:
210 sub SCALAR::split { [ split '', $_[0] ] }
211 sub ARRAY::length { scalar @{$_[0]} }
213 print "Hello, world!"->split->length();
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.
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.
223 The following example shows the range of valid arguments:
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
239 The INTEGER, FLOAT, NUMBER, STRING, SCALAR, ARRAY, HASH, CODE, UNDEF, DEFAULT and UNIVERSAL options can take
240 three different types of value:
248 use autobox INTEGER => 'MyInt';
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>.
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:
261 use autobox ARRAY => 'Prelude::';
265 use autobox ARRAY => 'Prelude::ARRAY';
269 A reference to an array of class names and/or namespaces. This associates multiple classes with the
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.
284 STRING => 'MyString',
285 DEFAULT => 'MyDefault';
290 STRING => 'MyString',
291 SCALAR => 'MyDefault',
292 ARRAY => 'MyDefault',
296 Which in turn is equivalent to:
299 INTEGER => 'MyDefault',
300 FLOAT => 'MyDefault',
301 STRING => [ 'MyString', 'MyDefault' ],
302 ARRAY => 'MyDefault',
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.
315 DEFAULT => 'MyNamespace::';
320 INTEGER => 'MyNamespace::SCALAR',
321 FLOAT => 'MyNamespace::SCALAR',
322 STRING => 'MyNamespace::SCALAR',
327 Any of the four default types can be exempted from defaulting to the DEFAULT value by supplying a value of undef:
331 DEFAULT => 'MyDefault';
333 42->foo # ok: MyDefault::foo
334 []->bar # ok: MyDefault::bar
336 %INC->baz # not ok: runtime error
340 The pseudotype, UNDEF, can be used to autobox undefined values. These are not autoboxed by default.
346 undef->foo() # runtime error
350 use autobox UNDEF => 'MyUndef';
356 use autobox UNDEF => 'MyNamespace::';
360 =head2 NUMBER, SCALAR and UNIVERSAL
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:
385 use autobox NUMBER => 'MyNumber';
390 INTEGER => 'MyNumber',
395 use autobox SCALAR => 'MyScalar';
400 INTEGER => 'MyScalar',
402 STRING => 'MyScalar';
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.
407 no autobox qw(NUMBER);
411 no autobox qw(INTEGER FLOAT);
413 Virtual type bindings can be mixed with ordinary bindings to provide fine-grained control over
414 inheritance and delegation. For instance:
417 INTEGER => 'MyInteger',
418 NUMBER => 'MyNumber',
419 SCALAR => 'MyScalar';
421 would result in the following bindings:
423 42->foo -> [ MyInteger, MyNumber, MyScalar ]
424 3.1415927->bar -> [ MyNumber, MyScalar ]
425 "Hello, world!->baz -> [ MyScalar ]
427 Note that DEFAULT bindings take precedence over virtual type bindings i.e.
430 UNIVERSAL => 'MyUniversal',
431 DEFAULT => 'MyDefault'; # default SCALAR, ARRAY, HASH and CODE before UNIVERSAL
436 INTEGER => [ 'MyDefault', 'MyUniversal' ],
437 FLOAT => [ 'MyDefault', 'MyUniversal' ], # ... &c.
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.
444 This allows the computed bindings to be seen in "longhand".
446 The option is ignored if the value corresponding to the C<DEBUG> key is false.
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.
451 Finally, if C<DEBUG> is true but not a CODE ref, the bindings are dumped
456 use autobox DEBUG => 1, ...
460 use autobox DEBUG => sub { ... }, ...
464 sub my_callback ($) {
469 use autobox DEBUG => \&my_callback, ...
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>.
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.:
483 package String::Trim;
485 use base qw(autobox);
489 $class->SUPER::import(STRING => 'String::Trim::Scalar');
492 package String::Trim::Scalar;
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.
506 This module can now be used without a C<use autobox> statement to enable the C<trim> method in the current
513 print " Hello, world! "->trim();
517 Although C<autobox> doesn't export anything, it includes an additional module, C<autobox::universal>,
518 which exports a single subroutine, C<type>.
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.
525 use autobox::universal qw(type);
527 type("Hello, world!") # STRING
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.
535 use autobox UNIVERSAL => 'autobox::universal';
538 3.1415927->type # FLOAT
545 Autoboxing comes at a price. Calling
547 "Hello, world!"->length()
549 is slightly slower than the equivalent method call on a string-like object, and significantly slower than
551 length("Hello, world!")
557 Due to Perl's precedence rules, some autoboxed literals may need to be parenthesized:
559 For instance, while this works:
561 my $curried = sub { ... }->curry();
565 my $curried = \&foo->curry();
567 The solution is to wrap the reference in parentheses:
569 my $curried = (\&foo)->curry();
571 The same applies for signed integer and float literals:
574 my $range = 10->to(1);
577 my $range = -10->to(10);
580 my $range = (-10)->to(10);
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:
588 print { foo => 'bar' }->foo();
591 print { 'foo', 'bar' }->foo();
594 print { 'foo', 'bar', @_ }->foo();
597 print { @_ }->foo() ? 1 : 0
599 In the latter case, the solution is to supply something
600 other than a HASH ref literal as the first argument
604 print STDOUT { @_ }->foo() ? 1 : 0;
607 my $hashref = { @_ };
608 print $hashref->foo() ? 1 : 0;
611 print '', { @_ }->foo() ? 1 : 0;
614 print '' . { @_ }->foo() ? 1 : 0;
617 { @_ }->print_if_foo(1, 0);
619 =head3 VERSION, import and unimport
621 Although C<can> and C<isa> work as expected for autoboxed values, the C<VERSION> method doesn't.
622 Thus, while these work:
626 3.1415->isa('MyScalar')
631 use autobox SCALAR => 'MyScalar';
633 print "Hello, world!"->VERSION();
637 print MyScalar->VERSION();
641 print $MyScalar::VERSION;
645 Likewise, C<import> and C<unimport> are unaffected by the autobox pragma:
647 # equivalent to Foo->import() rather than MyScalar->import('Foo')
650 # error: Can't call method "import" on unblessed reference
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
663 The workaround is to use autobox within the C<eval> e.g.
670 Note that the C<eval BLOCK> form works as expected:
674 eval { 42->foo() }; # OK
684 =item * L<autobox::Closure::Attributes|autobox::Closure::Attributes>
686 =item * L<autobox::Core|autobox::Core>
688 =item * L<autobox::DateTime::Duration|autobox::DateTime::Duration>
690 =item * L<autobox::Encode|autobox::Encode>
692 =item * L<Moose::Autobox>
694 =item * L<Perl6::Contexts|Perl6::Contexts>
696 =item * L<Scalar::Properties|Scalar::Properties>
698 =item * L<Shell::Autobox|Shell::Autobox>
704 chocolateboy <chocolate.boy@email.com>
708 Copyright (c) 2003-2008, chocolateboy.
710 This module is free software. It may be used, redistributed
711 and/or modified under the same terms as Perl itself.