1autobox::Core(3) User Contributed Perl Documentation autobox::Core(3)
2
3
4
6 autobox::Core - Provide core functions to autoboxed scalars, arrays and
7 hashes.
8
10 use autobox::Core;
11
12 "Hello, World\n"->uc->print;
13
14 my @list = (1, 5, 9, 2, 0, 4, 2, 1);
15 @list->sort->reverse->print;
16
17 # works with references too!
18 my $list = [1, 5, 9, 2, 0, 4, 2, 1];
19 $list->sort->reverse->print;
20
21 my %hash = (
22 grass => 'green',
23 apple => 'red',
24 sky => 'blue',
25 );
26
27 [10, 20, 30, 40, 50]->pop->say;
28 [10, 20, 30, 40, 50]->shift->say;
29
30 my $lala = "Lalalalala\n";
31 "chomp: "->concat($lala->chomp, " ", $lala)->say;
32
33 my $hashref = { foo => 10, bar => 20, baz => 30, qux => 40 };
34
35 print "hash keys: ", $hashref->keys->join(' '), "\n"; # or if you prefer...
36 print "hash keys: ", join ' ', $hashref->keys(), "\n"; # or
37 print "hash keys: "; $hashref->keys->say;
38
40 The autobox module promotes Perl's primitive types (literals (strings
41 and numbers), scalars, arrays and hashes) into first-class objects.
42 However, autobox does not provide any methods for these new classes.
43
44 autobox::CORE provides a set of methods for these new classes. It
45 includes almost everything in perlfunc, some things from Scalar::Util
46 and List::Util, and some Perl 5 versions of methods taken from Perl 6.
47
48 With autobox::Core one is able to change this:
49
50 print join(" ", reverse(split(" ", $string)));
51
52 to this:
53
54 use autobox::Core;
55
56 $string->split(" ")->reverse->print;
57
58 Likewise you can change this:
59
60 my $array_ref = [qw(fish dog cat elephant bird)];
61
62 push @$array_ref, qw(snake lizard giraffe mouse);
63
64 to this:
65
66 use autobox::Core;
67 my $array_ref = [qw(fish dog cat elephant bird)];
68
69 $array_ref->push( qw(snake lizard giraffe mouse));
70
71 autobox::Core makes it easier to avoid parentheses pile ups and messy
72 dereferencing syntaxes.
73
74 autobox::Core is mostly glue. It presents existing functions with a
75 new interface, while adding few extra. Most of the methods read like
76 "sub hex { CORE::hex($_[0]) }". In addition to built-ins from perlfunc
77 that operate on hashes, arrays, scalars, and code references, some Perl
78 6-ish things have been included, and some keywords like "foreach" are
79 represented too.
80
81 What's Implemented?
82 · Many of the functions listed in perlfunc under the headings:
83
84 · "Functions for real @ARRAYs",
85
86 · "Functions for real %HASHes",
87
88 · "Functions for list data",
89
90 · "Functions for SCALARs or strings"
91
92 plus a few taken from other sections and documented below.
93
94 · Some methods from Scalar::Util and List::Util.
95
96 · Some things expected in Perl 6, such as "last" ("last_idx"),
97 "elems", and "curry".
98
99 · "flatten" explicitly flattens an array.
100
101 String Methods
102
103 String methods are of the form "my $return = $string->method(@args)".
104 Some will act on the $string and some will return a new string.
105
106 Many string methods are simply wrappers around core functions, but
107 there are additional operations and modifications to core behavior.
108
109 Anything which takes a regular expression, such as split and m, usually
110 take it in the form of a compiled regex ("qr//"). Any modifiers can be
111 attached to the "qr" normally. Bare strings may be used in place of
112 regular expressions, and Perl will compile it to a regex, as usual.
113
114 These built in functions are implemented for scalars, they work just
115 like normal: chomp, chop,chr crypt, index, lc lcfirst, length, ord,
116 pack, reverse (always in scalar context), rindex, sprintf, substr, uc
117 ucfirst, unpack, quotemeta, vec, undef, split, system, eval.
118
119 In addition, so are each of the following:
120
121 concat
122
123 $string1->concat($string2);
124
125 Concatenates $string2 to $string1. This corresponds to the "." operator
126 used to join two strings. Returns the joined strings.
127
128 strip
129
130 Removes whitespace from the beginning and end of a string.
131
132 " \t \n \t foo \t \n \t "->strip; # foo
133
134 This is redundant and subtly different from "trim" which allows for the
135 removal of specific characters from the beginning and end of a string.
136
137 trim
138
139 Removes whitespace from the beginning and end of a string. "trim" can
140 also remove specific characters from the beginning and the end of
141 string.
142
143 ' hello'->trim; # 'hello'
144 '*+* hello *+*'->trim("*+"); # ' hello '
145 ' *+* hello *+*'->trim("*+"); # ' *+* hello'
146
147 ltrim
148
149 Just like trim but it only trims the left side (start) of the string.
150
151 ' hello'->ltrim; # 'hello'
152 '*+* hello *+*'->ltrim("*+"); # ' hello *+*'
153
154 rtrim
155
156 Just like trim but it only trims the right side (end) of the string.
157
158 'hello '->rtrim; # 'hello'
159 '*+* hello *+*'->rtrim("*+"); # '*+* hello '
160
161 split
162
163 my @split_string = $string->split(qr/.../);
164 my @split_string = $string->split(' ');
165
166 A wrapper around split. It takes the regular expression as a compiled
167 regex, or a string which Perl parses as a regex.
168
169 print "10, 20, 30, 40"->split(qr{, ?})->elements, "\n";
170 "hi there"->split(qr/ */); # h i t h e r e
171
172 The limit argument is not implemented.
173
174 title_case
175
176 "title_case" converts the first character of each word in the string to
177 upper case.
178
179 "this is a test"->title_case; # This Is A Test
180
181 center
182
183 my $centered_string = $string->center($length);
184 my $centered_string = $string->center($length, $character);
185
186 Centers $string between $character. $centered_string will be of length
187 $length, or the length of $string, whichever is greater.
188
189 $character defaults to " ".
190
191 say "Hello"->center(10); # " Hello ";
192 say "Hello"->center(10, '-'); # "---Hello--";
193
194 "center()" will never truncate $string. If $length is less than
195 "$string->length" it will just return $string.
196
197 say "Hello"->center(4); # "Hello";
198
199 qx
200
201 my $output = $string->qx;
202
203 Runs $string as a command just enclosing it backticks, as in
204 "`$string`".
205
206 nm
207
208 if( $foo->nm(qr/bar/) ) {
209 say "$foo did not match 'bar'";
210 }
211
212 "Negative match". Corresponds to "!~". Otherwise works in the same
213 way as "m()".
214
215 m
216
217 if( $foo->m(qr/bar/) ) {
218 say "$foo matched 'bar'";
219 }
220
221 my $matches = $foo->m( qr/(\d*) (\w+)/ );
222 say $matches->[0];
223 say $matches->[1];
224
225 Works the same as "m//", but the regex must be passed in as a "qr//".
226
227 "m" returns an array reference so that list functions such as "map" and
228 "grep" may be called on the result. Use "elements" to turn this into a
229 list of values.
230
231 my ($street_number, $street_name, $apartment_number) =
232 "1234 Robin Drive #101"->m( qr{(\d+) (.*)(?: #(\d+))?} )->elements;
233
234 print "$street_number $street_name $apartment_number\n";
235
236 s
237
238 my $string = "the cat sat on the mat";
239 $string->s( qr/cat/, "dog" );
240 $string->say; # the dog sat on the mat
241
242 String substitution. Works similarly to "s///". In boolean context,
243 it returns true/false to indicate whether the substitution succeeded.
244 "if", "?:", "!", and so on, all provide boolean context. It either
245 fails or succeeds, having replaced only one occurrence on success -- it
246 doesn't replace globally. In scalar context other than boolean
247 context, it returns the modified string (incompatible change, new as of
248 v 1.31).
249
250 undef
251
252 $string->undef;
253
254 Assigns "undef" to the $string.
255
256 defined
257
258 my $is_defined = $string->defined;
259
260 if( not $string->defined ) {
261 # give $string a value...
262 }
263
264 "defined" tests whether a value is defined (not "undef").
265
266 repeat
267
268 my $repeated_string = $string->repeat($n);
269
270 Like the "x" operator, repeats a string $n times.
271
272 print 1->repeat(5); # 11111
273 print "\n"->repeat(10); # ten newlines
274
275 I/O Methods
276
277 These are methods having to do with input and ouptut, not filehandles.
278
279 print
280
281 $string->print;
282
283 Prints a string or a list of strings. Returns true if successful.
284
285 say
286
287 Like print, but implicitly appends a newline to the end.
288
289 $string->say;
290
291 Boolean Methods
292
293 Methods related to boolean operations.
294
295 and
296
297 "and" corresponds to "&&". Returns true if both operands are true.
298
299 if( $a->and($b) ) {
300 ...
301 }
302
303 not
304
305 "not" corresponds to "!". Returns true if the subject is false.
306
307 if( $a->not ) {
308 ...
309 }
310
311 or
312
313 "or" corresponds to "||". Returns true if at least one of the operands
314 is true.
315
316 if( $a->or($b) ) {
317 ...
318 }
319
320 xor
321
322 "xor" corresponds to "xor". Returns true if only one of the operands
323 is true.
324
325 if( $a->xor($b) ) {
326 ...
327 }
328
329 Number Related Methods
330
331 Methods related to numbers.
332
333 The basic built in functions which operate as normal : abs, atan2, cos,
334 exp, int, log, oct, hex, sin, and sqrt.
335
336 The following operators were also included:
337
338 dec
339
340 $number->dec();
341 # $number is smaller by 1.
342
343 "dec" corresponds to "++". Decrements subject, will decrement
344 character strings too: 'b' decrements to 'a'.
345
346 inc
347
348 "inc" corresponds to "++". Increments subject, will increment
349 character strings too. 'a' increments to 'b'.
350
351 mod
352
353 "mod" corresponds to "%".
354
355 $number->mod(5);
356
357 pow
358
359 "pow" returns $number raised to the power of the $exponent.
360
361 my $result = $number->pow($expontent);
362 print 2->pow(8); # 256
363
364 is_number
365
366 $is_a_number = $thing->is_number;
367
368 Returns true if $thing is a number as understood by Perl.
369
370 12.34->is_number; # true
371 "12.34"->is_number; # also true
372
373 is_positive
374
375 $is_positive = $thing->is_positive;
376
377 Returns true if $thing is a positive number.
378
379 0 is not positive.
380
381 is_negative
382
383 $is_negative = $thing->is_negative;
384
385 Returns true if $thing is a negative number.
386
387 0 is not negative.
388
389 is_integer
390
391 $is_an_integer = $thing->is_integer;
392
393 Returns true if $thing is an integer.
394
395 12->is_integer; # true
396 12.34->is_integer; # false
397
398 is_int
399
400 A synonym for is_integer.
401
402 is_decimal
403
404 $is_a_decimal_number = $thing->is_decimal;
405
406 Returns true if $thing is a decimal number.
407
408 12->is_decimal; # false
409 12.34->is_decimal; # true
410 ".34"->is_decimal; # true
411
412 Reference Related Methods
413
414 The following core functions are implemented.
415
416 tie, tied, ref, vec.
417
418 "tie", "tied", and "undef" don't work on code references.
419
420 Array Methods
421
422 Array methods work on both arrays and array references:
423
424 my $arr = [ 1 .. 10 ];
425 $arr->undef;
426
427 Or:
428
429 my @arr = ( 1 .. 10 );
430 @arr->undef;
431
432 List context forces methods to return a list:
433
434 my @arr = ( 1 .. 10 );
435 print join ' -- ', @arr->grep(sub { $_ > 3 }), "\n";
436
437 Likewise, scalar context forces methods to return an array reference.
438
439 As scalar context forces methods to return a reference, methods may be
440 chained
441
442 my @arr = ( 1 .. 10 );
443 @arr->grep(sub { $_ > 3 })->min->say; # "4\n";
444
445 These built-in functions are defined as methods:
446
447 pop, push, shift, unshift, delete, undef, exists, bless, tie, tied,
448 ref, grep, map, join, reverse, and sort, each.
449
450 As well as:
451
452 vdelete
453
454 Deletes a specified value from the array.
455
456 $a = 1->to(10);
457 $a->vdelete(3); # deletes 3
458 $a->vdelete(2)->say; # "1 4 5 6 7 8 9 10\n"
459
460 uniq
461
462 Removes all duplicate elements from an array and returns the new array
463 with no duplicates.
464
465 my @array = qw( 1 1 2 3 3 6 6 );
466 @return = @array->uniq; # @return : 1 2 3 6
467
468 first
469
470 Returns the first element of an array for which a callback returns
471 true:
472
473 $arr->first(sub { qr/5/ });
474
475 max
476
477 Returns the largest numerical value in the array.
478
479 $a = 1->to(10);
480 $a->max; # 10
481
482 min
483
484 Returns the smallest numerical value in the array.
485
486 $a = 1->to(10);
487 $a->min; # 1
488
489 mean
490
491 Returns the mean of elements of an array.
492
493 $a = 1->to(10);
494 $a->mean; # 55/10
495
496 var
497
498 Returns the variance of the elements of an array.
499
500 $a = 1->to(10);
501 $a->var; # 33/4
502
503 svar
504
505 Returns the standard variance.
506
507 $a = 1->to(10);
508 $a->svar; # 55/6
509
510 at
511
512 Returns the element at a specified index. This function does not modify
513 the original array.
514
515 $a = 1->to(10);
516 $a->at(2); # 3
517
518 size, elems, length
519
520 "size", "elems" and "length" all return the number of elements in an
521 array.
522
523 my @array = qw(foo bar baz);
524 @array->size; # 3
525
526 elements, flatten
527
528 my @copy_of_array = $array->flatten;
529
530 Returns the elements of an array ref as an array. This is the same as
531 "@{$array}".
532
533 Arrays can be iterated on using "for" and "foreach". Both take a code
534 reference as the body of the for statement.
535
536 foreach
537
538 @array->foreach(\&code);
539
540 Calls &code on each element of the @array in order. &code gets the
541 element as its argument.
542
543 @array->foreach(sub { print $_[0] }); # print each element of the array
544
545 for
546
547 @array->for(\&code);
548
549 Like foreach, but &code is called with the index, the value and the
550 array itself.
551
552 my $arr = [ 1 .. 10 ];
553 $arr->for(sub {
554 my($idx, $value) = @_;
555 print "Value #$idx is $value\n";
556 });
557
558 sum
559
560 my $sum = @array->sum;
561
562 Adds together all the elements of the array.
563
564 count
565
566 Returns the number of elements in array that are "eq" to a specified
567 value:
568
569 my @array = qw/one two two three three three/;
570 my $num = @array->count('three'); # returns 3
571
572 to, upto, downto
573
574 "to", "upto", and "downto" create array references:
575
576 1->to(5); # creates [1, 2, 3, 4, 5]
577 1->upto(5); # creates [1, 2, 3, 4, 5]
578 5->downto(5); # creates [5, 4, 3, 2, 1]
579
580 Those wrap the ".." operator.
581
582 Note while working with negative numbers you need to use () so as to
583 avoid the wrong evaluation.
584
585 my $range = 10->to(1); # this works
586 my $range = -10->to(10); # wrong, interpreted as -( 10->to(10) )
587 my $range = (-10)->to(10); # this works
588
589 head
590
591 Returns the first element from @list. This differs from shift in that
592 it does not change the array.
593
594 my $first = @list->head;
595
596 tail
597
598 Returns all but the first element from @list.
599
600 my @list = qw(foo bar baz quux);
601 my @rest = @list->tail; # [ 'bar', 'baz', 'quux' ]
602
603 Optionally, you can pass a number as argument to ask for the last $n
604 elements:
605
606 @rest = @list->tail(2); # [ 'baz', 'quux' ]
607
608 slice
609
610 Returns a list containing the elements from @list at the indices
611 @indices. In scalar context, returns an array reference.
612
613 # Return $list[1], $list[2], $list[4] and $list[8].
614 my @sublist = @list->slice(1,2,4,8);
615
616 range
617
618 "range" returns a list containing the elements from @list with indices
619 ranging from $lower_idx to $upper_idx. It returns an array reference in
620 scalar context.
621
622 my @sublist = @list->range( $lower_idx, $upper_idx );
623
624 last_index
625
626 my $index = @array->last_index(qr/.../);
627
628 Returns the highest index whose element matches the given regular
629 expression.
630
631 my $index = @array->last_index(\&filter);
632
633 Returns the highest index for an element on which the filter returns
634 true. The &filter is passed in each value of the @array.
635
636 my @things = qw(pear poll potato tomato);
637 my $last_p = @things->last_index(qr/^p/); # 2
638
639 Called with no arguments, it corresponds to $#array giving the highest
640 index of the array.
641
642 my $index = @array->last_index;
643
644 first_index
645
646 Works just like last_index but it will return the index of the first
647 matching element.
648
649 my $first_index = @array->first_index; # 0
650
651 my @things = qw(pear poll potato tomato);
652 my $last_p = @things->first_index(qr/^t/); # 3
653
654 at
655
656 my $value = $array->at($index);
657
658 Equivalent to "$array->[$index]".
659
660 Hash Methods
661
662 Hash methods work on both hashes and hash references.
663
664 The built in functions work as normal:
665
666 delete, exists, keys, values, bless, tie, tied, ref, undef,
667
668 at, get
669
670 my @values = %hash->get(@keys);
671
672 Returns the @values of @keys.
673
674 put
675
676 %hash->put(%other_hash);
677
678 Overlays %other_hash on top of %hash.
679
680 my $h = {a => 1, b => 2};
681 $h->put(b => 99, c => 3); # (a => 1, b => 99, c => 3)
682
683 set
684
685 Synonym for put.
686
687 each
688
689 Like "foreach" but for hash references. For each key in the hash, the
690 code reference is invoked with the key and the corresponding value as
691 arguments:
692
693 my $hashref = { foo => 10, bar => 20, baz => 30, quux => 40 };
694 $hashref->each(sub { print $_[0], ' is ', $_[1], "\n" });
695
696 Or:
697
698 my %hash = ( foo => 10, bar => 20, baz => 30, quux => 40 );
699 %hash->each(sub { print $_[0], ' is ', $_[1], "\n" });
700
701 Unlike regular "each", this each will always iterate through the entire
702 hash.
703
704 Hash keys appear in random order that varies from run to run (this is
705 intentional, to avoid calculated attacks designed to trigger
706 algorithmic worst case scenario in "perl"'s hash tables).
707
708 You can get a sorted "foreach" by combining "keys", "sort", and
709 "foreach":
710
711 %hash->keys->sort->foreach(sub {
712 print $_[0], ' is ', $hash{$_[0]}, "\n";
713 });
714
715 lock_keys
716
717 %hash->lock_keys;
718
719 Works as "lock_keys" in Hash::Util. No more keys may be added to the
720 hash.
721
722 slice
723
724 Takes a list of hash keys and returns the corresponding values e.g.
725
726 my %hash = (
727 one => 'two',
728 three => 'four',
729 five => 'six'
730 );
731
732 print %hash->slice(qw(one five))->join(' and '); # prints "two and six"
733
734 flip
735
736 Exchanges values for keys in a hash:
737
738 my %things = ( foo => 1, bar => 2, baz => 5 );
739 my %flipped = %things->flip; # { 1 => foo, 2 => bar, 5 => baz }
740
741 If there is more than one occurrence of a certain value, any one of the
742 keys may end up as the value. This is because of the random ordering
743 of hash keys.
744
745 # Could be { 1 => foo }, { 1 => bar }, or { 1 => baz }
746 { foo => 1, bar => 1, baz => 1 }->flip;
747
748 Because references cannot usefully be keys, it will not work where the
749 values are references.
750
751 { foo => [ 'bar', 'baz' ] }->flip; # dies
752
753 flatten
754
755 my %hash = $hash_ref->flatten;
756
757 Dereferences a hash reference.
758
759 Code Methods
760
761 Methods which work on code references.
762
763 These are simple wrappers around the Perl core functions. bless, ref,
764
765 Due to Perl's precedence rules, some autoboxed literals may need to be
766 parenthesized. For instance, this works:
767
768 my $curried = sub { ... }->curry();
769
770 This does not:
771
772 my $curried = \&foo->curry();
773
774 The solution is to wrap the reference in parentheses:
775
776 my $curried = (\&foo)->curry();
777
778 curry
779
780 my $curried_code = $code->curry(5);
781
782 Currying takes a code reference and provides the same code, but with
783 the first argument filled in.
784
785 my $greet_world = sub {
786 my($greeting, $place) = @_;
787 return "$greeting, $place!";
788 };
789 print $greet_world->("Hello", "world"); # "Hello, world!"
790
791 my $howdy_world = $greet_world->curry("Howdy");
792 print $howdy_world->("Texas"); # "Howdy, Texas!"
793
794 What's Missing?
795 · File and socket operations are already implemented in an object-
796 oriented fashion care of IO::Handle, IO::Socket::INET, and IO::Any.
797
798 · Functions listed in the perlfunc headings
799
800 · "System V interprocess communication functions",
801
802 · "Fetching user and group info",
803
804 · "Fetching network info",
805
806 · "Keywords related to perl modules",
807
808 · "Functions for processes and process groups",
809
810 · "Keywords related to scoping",
811
812 · "Time-related functions",
813
814 · "Keywords related to the control flow of your perl program",
815
816 · "Functions for filehandles, files, or directories",
817
818 · "Input and output functions".
819
820 · (Most) binary operators
821
822 These things are likely implemented in an object oriented fashion by
823 other CPAN modules, are keywords and not functions, take no arguments,
824 or don't make sense as part of the string, number, array, hash, or code
825 API.
826
827 Autoboxing
828 This section quotes four pages from the manuscript of Perl 6 Now: The
829 Core Ideas Illustrated with Perl 5 by Scott Walters. The text appears
830 in the book starting at page 248. This copy lacks the benefit of
831 copyedit - the finished product is of higher quality.
832
833 A box is an object that contains a primitive variable. Boxes are used
834 to endow primitive types with the capabilities of objects which
835 essential in strongly typed languages but never strictly required in
836 Perl. Programmers might write something like "my $number =
837 Int->new(5)". This is manual boxing. To autobox is to convert a
838 simple type into an object type automatically, or only conceptually.
839 This is done by the language.
840
841 autoboxing makes a language look to programmers as if everything is an
842 object while the interpreter is free to implement data storage however
843 it pleases. Autoboxing is really making simple types such as numbers,
844 strings, and arrays appear to be objects.
845
846 "int", "num", "bit", "str", and other types with lower case names, are
847 primitives. They're fast to operate on, and require no more memory to
848 store than the data held strictly requires. "Int", "Num", "Bit",
849 "Str", and other types with an initial capital letter, are objects.
850 These may be subclassed (inherited from) and accept traits, among other
851 things. These objects are provided by the system for the sole purpose
852 of representing primitive types as objects, though this has many
853 ancillary benefits such as making "is" and "has" work. Perl provides
854 "Int" to encapsulate an "int", "Num" to encapsulate a "num", "Bit" to
855 encapsulate a "bit", and so on. As Perl's implementations of hashes
856 and dynamically expandable arrays store any type, not just objects,
857 Perl programmers almost never are required to box primitive types in
858 objects. Perl's power makes this feature less essential than it is in
859 other languages.
860
861 autoboxing makes primitive objects and they're boxed versions
862 equivalent. An "int" may be used as an "Int" with no constructor call,
863 no passing, nothing. This applies to constants too, not just
864 variables. This is a more Perl 6 way of doing things.
865
866 # Perl 6 - autoboxing associates classes with primitives types:
867
868 print 4.sqrt, "\n";
869
870 print [ 1 .. 20 ].elems, "\n";
871
872 The language is free to implement data storage however it wishes but
873 the programmer sees the variables as objects.
874
875 Expressions using autoboxing read somewhat like Latin suffixes. In the
876 autoboxing mind-set, you might not say that something is "made more
877 mnemonic", but has been "mnemonicified".
878
879 Autoboxing may be mixed with normal function calls. In the case where
880 the methods are available as functions and the functions are available
881 as methods, it is only a matter of personal taste how the expression
882 should be written:
883
884 # Calling methods on numbers and strings, these three lines are equivalent
885 # Perl 6
886
887 print sqrt 4;
888 print 4.sqrt;
889 4.sqrt.print;
890
891 The first of these three equivalents assumes that a global "sqrt()"
892 function exists. This first example would fail to operate if this
893 global function were removed and only a method in the "Num" package was
894 left.
895
896 Perl 5 had the beginnings of autoboxing with filehandles:
897
898 use IO::Handle;
899 open my $file, '<', 'file.txt' or die $!;
900 $file->read(my $data, -s $file);
901
902 Here, "read" is a method on a filehandle we opened but never blessed.
903 This lets us say things like "$file->print(...)" rather than the often
904 ambagious "print $file ...".
905
906 To many people, much of the time, it makes more conceptual sense as
907 well.
908
909 Reasons to Box Primitive Types
910
911 What good is all of this?
912
913 · Makes conceptual sense to programmers used to object interfaces as
914 the way to perform options.
915
916 · Alternative idiom. Doesn't require the programmer to write or read
917 expressions with complex precedence rules or strange operators.
918
919 · Many times that parenthesis would otherwise have to span a large
920 expression, the expression may be rewritten such that the
921 parenthesis span only a few primitive types.
922
923 · Code may often be written with fewer temporary variables.
924
925 · Autoboxing provides the benefits of boxed types without the memory
926 bloat of actually using objects to represent primitives. Autoboxing
927 "fakes it".
928
929 · Strings, numbers, arrays, hashes, and so on, each have their own
930 API. Documentation for an "exists" method for arrays doesn't have
931 to explain how hashes are handled and vice versa.
932
933 · Perl tries to accommodate the notion that the "subject" of a
934 statement should be the first thing on the line, and autoboxing
935 furthers this agenda.
936
937 Perl is an idiomatic language and this is an important idiom.
938
939 Subject First: An Aside
940
941 Perl's design philosophy promotes the idea that the language should be
942 flexible enough to allow programmers to place the subject of a
943 statement first. For example, "die $! unless read $file, 60" looks
944 like the primary purpose of the statement is to "die".
945
946 While that might be the programmers primary goal, when it isn't, the
947 programmer can communicate his real primary intention to programmers by
948 reversing the order of clauses while keeping the exact same logic:
949 "read $file, 60 or die $!".
950
951 Autoboxing is another way of putting the subject first.
952
953 Nouns make good subjects, and in programming, variables, constants, and
954 object names are the nouns. Function and method names are verbs.
955 "$noun->verb()" focuses the readers attention on the thing being acted
956 on rather than the action being performed. Compare to "$verb($noun)".
957
958 Autoboxing and Method Results
959
960 Let's look at some examples of ways an expression could be written.
961
962 # Various ways to do the same thing:
963
964 print(reverse(sort(keys(%hash)))); # Perl 5 - pathological parenthetic
965 print reverse sort keys %hash; # Perl 5 - no unneeded parenthesis
966
967 print(reverse(sort(%hash,keys)))); # Perl 6 - pathological
968 print reverse sort %hash.keys; # Perl 6 - no unneeded parenthesis
969
970 %hash.keys ==> sort ==> reverse ==> print; # Perl 6 - pipeline operator
971
972 %hash.keys.sort.reverse.print; # Perl 6 - autobox
973
974 %hash->keys->sort->reverse->print; # Perl 5 - autobox
975
976 This section deals with the last two of these equivalents. These are
977 method calls
978
979 use autobox::Core;
980 use Perl6::Contexts;
981
982 my %hash = (foo => 'bar', baz => 'quux');
983
984 %hash->keys->sort->reverse->print; # Perl 5 - autobox
985
986 # prints "foo baz"
987
988 Each method call returns an array reference, in this example. Another
989 method call is immediately performed on this value. This feeding of
990 the next method call with the result of the previous call is the common
991 mode of use of autoboxing. Providing no other arguments to the method
992 calls, however, is not common.
993
994 "Perl6::Contexts" recognizes object context as provided by "->" and
995 coerces %hash and @array into references, suitable for use with
996 "autobox". (Note that "autobox" also does this automatically as of
997 version 2.40.)
998
999 "autobox" associates primitive types, such as references of various
1000 sorts, with classes. "autobox::Core" throws into those classes methods
1001 wrapping Perl's built-in functions. In the interest of full
1002 disclosure, "Perl6::Contexts" and "autobox::Core" are my creations.
1003
1004 Autobox to Simplify Expressions
1005
1006 One of my pet peeves in programming is parenthesis that span large
1007 expression. It seems like about the time I'm getting ready to close
1008 the parenthesis I opened on the other side of the line, I realize that
1009 I've forgotten something, and I have to arrow back over or grab the
1010 mouse.
1011
1012 When the expression is too long to fit on a single line, it gets broken
1013 up, then I must decide how to indent it if it grows to 3 or more lines.
1014
1015 # Perl 5 - a somewhat complex expression
1016
1017 print join("\n", map { CGI::param($_) } @cgi_vars), "\n";
1018 # Perl 5 - again, using autobox:
1019
1020 @cgi_vars->map(sub { CGI::param($_[0]) })->join("\n")->concat("\n")->print;
1021
1022 The autoboxed version isn't shorter, but it reads from left to right,
1023 and the parenthesis from the "join()" don't span nearly as many
1024 characters. The complex expression serving as the value being
1025 "join()"ed in the non-autoboxed version becomes, in the autoboxed
1026 version, a value to call the "join()" method on.
1027
1028 This "print" statement takes a list of CGI parameter names, reads the
1029 values for each parameter, joins them together with newlines, and
1030 prints them with a newline after the last one.
1031
1032 Pretending that this expression were much larger and it had to be
1033 broken to span several lines, or pretending that comments are to be
1034 placed after each part of the expression, you might reformat it as
1035 such:
1036
1037 @cgi_vars->map(sub { CGI::param($_[0]) }) # turn CGI arg names into values
1038 ->join("\n") # join with newlines
1039 ->concat("\n") # give it a trailing newline
1040 ->print; # print them all out
1041
1042 Here ends the text quoted from the Perl 6 Now manuscript.
1043
1045 Yes. Report them to the author, scott@slowass.net, or post them to
1046 GitHub's bug tracker at
1047 <https://github.com/scrottie/autobox-Core/issues>.
1048
1049 The API is not yet stable -- Perl 6-ish things and local extensions are
1050 still being renamed.
1051
1053 See the Changes file.
1054
1056 Copyright (C) 2009, 2010, 2011 by Scott Walters and various
1057 contributors listed (and unlisted) below.
1058
1059 This library is free software; you can redistribute it and/or modify it
1060 under the same terms as Perl itself, either Perl version 5.8.9 or, at
1061 your option, any later version of Perl 5 you may have available.
1062
1063 This library is distributed in the hope that it will be useful, but
1064 without any warranty; without even the implied warranty of
1065 merchantability or fitness for a particular purpose.
1066
1068 autobox
1069 Moose::Autobox
1070 Perl6::Contexts
1071 <http://github.com/gitpan/autobox-Core>
1072 IO::Any
1073 Perl 6: <http://dev.perl.org/perl6/apocalypse/>.
1074
1076 Scott Walters, scott@slowass.net.
1077
1078 Tomasz Konojacki has been assisting with maint.
1079
1080 Jacinta Richardson improved documentation and tidied up the interface.
1081
1082 Michael Schwern and the perl5i contributors for tests, code, and
1083 feedback.
1084
1085 JJ contributed a "strip" method for scalars - thanks JJ!
1086
1087 Ricardo SIGNES contributed patches.
1088
1089 Thanks to Matt Spear, who contributed tests and definitions for numeric
1090 operations.
1091
1092 Mitchell N Charity reported a bug and sent a fix.
1093
1094 Thanks to chocolateboy for autobox and for the encouragement.
1095
1096 Thanks to Bruno Vecchi for bug fixes and many, many new tests going
1097 into version 0.8.
1098
1099 Thanks to <http://github.com/daxim> daxim/Lars DIECKOW pushing in fixes
1100 and patches from the RT queue along with fixes to build and additional
1101 doc examples.
1102
1103 Thanks to Johan Lindstrom for bug reports.
1104
1105 Thanks to everyone else who sent fixes or suggestions -- apologies if I
1106 failed to include you here!
1107
1108
1109
1110perl v5.30.0 2019-07-26 autobox::Core(3)