1autobox::Core(3)      User Contributed Perl Documentation     autobox::Core(3)
2
3
4

NAME

6       autobox::Core - Provide core functions to autoboxed scalars, arrays and
7       hashes.
8

SYNOPSIS

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

DESCRIPTION

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 `$string`.
204
205       nm
206
207           if( $foo->nm(qr/bar/) ) {
208               say "$foo did not match 'bar'";
209           }
210
211       "Negative match".  Corresponds to "!~".  Otherwise works in the same
212       way as m().
213
214       m
215
216           if( $foo->m(qr/bar/) ) {
217               say "$foo matched 'bar'";
218           }
219
220           my $matches = $foo->m( qr/(\d*) (\w+)/ );
221           say $matches->[0];
222           say $matches->[1];
223
224       Works the same as "m//", but the regex must be passed in as a "qr//".
225
226       "m" returns an array reference so that list functions such as "map" and
227       "grep" may be called on the result.  Use "elements" to turn this into a
228       list of values.
229
230         my ($street_number, $street_name, $apartment_number) =
231             "1234 Robin Drive #101"->m( qr{(\d+) (.*)(?: #(\d+))?} )->elements;
232
233         print "$street_number $street_name $apartment_number\n";
234
235       s
236
237         my $string = "the cat sat on the mat";
238         $string->s( qr/cat/, "dog" );
239         $string->say;                 # the dog sat on the mat
240
241       String substitution.  Works similarly to "s///".  In boolean context,
242       it returns true/false to indicate whether the substitution succeeded.
243       "if", "?:", "!", and so on, all provide boolean context.  It either
244       fails or succeeds, having replaced only one occurrence on success -- it
245       doesn't replace globally.  In scalar context other than boolean
246       context, it returns the modified string (incompatible change, new as of
247       v 1.31).
248
249       undef
250
251           $string->undef;
252
253       Assigns "undef" to the $string.
254
255       defined
256
257           my $is_defined = $string->defined;
258
259           if( not $string->defined ) {
260               # give $string a value...
261           }
262
263       "defined" tests whether a value is defined (not "undef").
264
265       repeat
266
267           my $repeated_string = $string->repeat($n);
268
269       Like the "x" operator, repeats a string $n times.
270
271           print 1->repeat(5);     # 11111
272           print "\n"->repeat(10); # ten newlines
273
274       I/O Methods
275
276       These are methods having to do with input and ouptut, not filehandles.
277
278       print
279
280           $string->print;
281
282       Prints a string or a list of strings.  Returns true if successful.
283
284       say
285
286       Like print, but implicitly appends a newline to the end.
287
288            $string->say;
289
290       Boolean Methods
291
292       Methods related to boolean operations.
293
294       and
295
296       "and" corresponds to "&&".  Returns true if both operands are true.
297
298               if( $a->and($b) ) {
299                   ...
300               }
301
302       not
303
304       "not" corresponds to "!".  Returns true if the subject is false.
305
306               if( $a->not ) {
307                   ...
308               }
309
310       or
311
312       "or" corresponds to "||".  Returns true if at least one of the operands
313       is true.
314
315               if( $a->or($b) ) {
316                   ...
317               }
318
319       xor
320
321       "xor" corresponds to "xor".  Returns true if only one of the operands
322       is true.
323
324               if( $a->xor($b) ) {
325                   ...
326               }
327
328       Number Related Methods
329
330       Methods related to numbers.
331
332       The basic built in functions which operate as normal : abs, atan2, cos,
333       exp, int, log, oct, hex, sin, and sqrt.
334
335       The following operators were also included:
336
337       dec
338
339           $number->dec();
340           # $number is smaller by 1.
341
342       "dec" corresponds to "++".  Decrements subject, will decrement
343       character strings too: 'b' decrements to 'a'.
344
345       inc
346
347       "inc" corresponds to "++".  Increments subject, will increment
348       character strings too. 'a' increments to 'b'.
349
350       mod
351
352       "mod" corresponds to "%".
353
354               $number->mod(5);
355
356       pow
357
358       "pow" returns $number raised to the power of the $exponent.
359
360           my $result = $number->pow($expontent);
361           print 2->pow(8);  # 256
362
363       is_number
364
365           $is_a_number = $thing->is_number;
366
367       Returns true if $thing is a number as understood by Perl.
368
369           12.34->is_number;           # true
370           "12.34"->is_number;         # also true
371
372       is_positive
373
374           $is_positive = $thing->is_positive;
375
376       Returns true if $thing is a positive number.
377
378       0 is not positive.
379
380       is_negative
381
382           $is_negative = $thing->is_negative;
383
384       Returns true if $thing is a negative number.
385
386       0 is not negative.
387
388       is_integer
389
390           $is_an_integer = $thing->is_integer;
391
392       Returns true if $thing is an integer.
393
394           12->is_integer;             # true
395           12.34->is_integer;          # false
396
397       is_int
398
399       A synonym for is_integer.
400
401       is_decimal
402
403           $is_a_decimal_number = $thing->is_decimal;
404
405       Returns true if $thing is a decimal number.
406
407           12->is_decimal;             # false
408           12.34->is_decimal;          # true
409           ".34"->is_decimal;          # true
410
411       Reference Related Methods
412
413       The following core functions are implemented.
414
415       tie, tied, ref, vec.
416
417       "tie", "tied", and "undef" don't work on code references.
418
419       Array Methods
420
421       Array methods work on both arrays and array references:
422
423         my $arr = [ 1 .. 10 ];
424         $arr->undef;
425
426       Or:
427
428         my @arr = ( 1 .. 10 );
429         @arr->undef;
430
431       List context forces methods to return a list:
432
433         my @arr = ( 1 .. 10 );
434         print join ' -- ', @arr->grep(sub { $_ > 3 }), "\n";
435
436       Likewise, scalar context forces methods to return an array reference.
437
438       As scalar context forces methods to return a reference, methods may be
439       chained
440
441         my @arr = ( 1 .. 10 );
442         @arr->grep(sub { $_ > 3 })->min->say;  # "4\n";
443
444       These built-in functions are defined as methods:
445
446       pop, push, shift, unshift, delete, undef, exists, bless, tie, tied,
447       ref, grep, map, join, reverse, and sort, each.
448
449       As well as:
450
451       vdelete
452
453       Deletes a specified value from the array.
454
455         $a = 1->to(10);
456         $a->vdelete(3);         # deletes 3
457         $a->vdelete(2)->say;    # "1 4 5 6 7 8 9 10\n"
458
459       uniq
460
461       Removes all duplicate elements from an array and returns the new array
462       with no duplicates.
463
464          my @array = qw( 1 1 2 3 3 6 6 );
465          @return = @array->uniq;    # @return : 1 2 3 6
466
467       first
468
469       Returns the first element of an array for which a callback returns
470       true:
471
472         $arr->first(sub { qr/5/ });
473
474       max
475
476       Returns the largest numerical value in the array.
477
478          $a = 1->to(10);
479          $a->max;           # 10
480
481       min
482
483       Returns the smallest numerical value in the array.
484
485          $a = 1->to(10);
486          $a->min;           # 1
487
488       mean
489
490       Returns the mean of elements of an array.
491
492          $a = 1->to(10);
493          $a->mean;          # 55/10
494
495       var
496
497       Returns the variance of the elements of an array.
498
499          $a = 1->to(10);
500          $a->var;           # 33/4
501
502       svar
503
504       Returns the standard variance.
505
506         $a = 1->to(10);
507         $a->svar;                     # 55/6
508
509       at
510
511       Returns the element at a specified index. This function does not modify
512       the original array.
513
514          $a = 1->to(10);
515          $a->at(2);                   # 3
516
517       size, elems, length
518
519       "size", "elems" and "length" all return the number of elements in an
520       array.
521
522          my @array = qw(foo bar baz);
523          @array->size;   # 3
524
525       elements, flatten
526
527           my @copy_of_array = $array->flatten;
528
529       Returns the elements of an array ref as an array.  This is the same as
530       "@{$array}".
531
532       Arrays can be iterated on using "for" and "foreach". Both take a code
533       reference as the body of the for statement.
534
535       foreach
536
537           @array->foreach(\&code);
538
539       Calls &code on each element of the @array in order.  &code gets the
540       element as its argument.
541
542           @array->foreach(sub { print $_[0] });  # print each element of the array
543
544       for
545
546           @array->for(\&code);
547
548       Like foreach, but &code is called with the index, the value and the
549       array itself.
550
551           my $arr = [ 1 .. 10 ];
552           $arr->for(sub {
553               my($idx, $value) = @_;
554               print "Value #$idx is $value\n";
555           });
556
557       sum
558
559           my $sum = @array->sum;
560
561       Adds together all the elements of the array.
562
563       count
564
565       Returns the number of elements in array that are "eq" to a specified
566       value:
567
568         my @array = qw/one two two three three three/;
569         my $num = @array->count('three');  # returns 3
570
571       to, upto, downto
572
573       "to", "upto", and "downto" create array references:
574
575          1->to(5);      # creates [1, 2, 3, 4, 5]
576          1->upto(5);    # creates [1, 2, 3, 4, 5]
577          5->downto(5);  # creates [5, 4, 3, 2, 1]
578
579       Those wrap the ".." operator.
580
581       Note while working with negative numbers you need to use () so as to
582       avoid the wrong evaluation.
583
584         my $range = 10->to(1);        # this works
585         my $range = -10->to(10);      # wrong, interpreted as -( 10->to(10) )
586         my $range = (-10)->to(10);    # this works
587
588       head
589
590       Returns the first element from @list.   This differs from shift in that
591       it does not change the array.
592
593           my $first = @list->head;
594
595       tail
596
597       Returns all but the first element from @list.
598
599           my @list = qw(foo bar baz quux);
600           my @rest = @list->tail;  # [ 'bar', 'baz', 'quux' ]
601
602       Optionally, you can pass a number as argument to ask for the last $n
603       elements:
604
605           @rest = @list->tail(2); # [ 'baz', 'quux' ]
606
607       slice
608
609       Returns a list containing the elements from @list at the indices
610       @indices. In scalar context, returns an array reference.
611
612           # Return $list[1], $list[2], $list[4] and $list[8].
613           my @sublist = @list->slice(1,2,4,8);
614
615       range
616
617       "range" returns a list containing the elements from @list with indices
618       ranging from $lower_idx to $upper_idx. It returns an array reference in
619       scalar context.
620
621           my @sublist = @list->range( $lower_idx, $upper_idx );
622
623       last_index
624
625           my $index = @array->last_index(qr/.../);
626
627       Returns the highest index whose element matches the given regular
628       expression.
629
630           my $index = @array->last_index(\&filter);
631
632       Returns the highest index for an element on which the filter returns
633       true.  The &filter is passed in each value of the @array.
634
635           my @things = qw(pear poll potato tomato);
636           my $last_p = @things->last_index(qr/^p/); # 2
637
638       Called with no arguments, it corresponds to $#array giving the highest
639       index of the array.
640
641           my $index = @array->last_index;
642
643       first_index
644
645       Works just like last_index but it will return the index of the first
646       matching element.
647
648           my $first_index = @array->first_index;    # 0
649
650           my @things = qw(pear poll potato tomato);
651           my $last_p = @things->first_index(qr/^t/); # 3
652
653       at
654
655           my $value = $array->at($index);
656
657       Equivalent to "$array->[$index]".
658
659       Hash Methods
660
661       Hash methods work on both hashes and hash references.
662
663       The built in functions work as normal:
664
665       delete, exists, keys, values, bless, tie, tied, ref, undef,
666
667       at, get
668
669           my @values = %hash->get(@keys);
670
671       Returns the @values of @keys.
672
673       put
674
675           %hash->put(%other_hash);
676
677       Overlays %other_hash on top of %hash.
678
679          my $h = {a => 1, b => 2};
680          $h->put(b => 99, c => 3);    # (a => 1, b => 99, c => 3)
681
682       set
683
684       Synonym for put.
685
686       each
687
688       Like "foreach" but for hash references. For each key in the hash, the
689       code reference is invoked with the key and the corresponding value as
690       arguments:
691
692         my $hashref = { foo => 10, bar => 20, baz => 30, quux => 40 };
693         $hashref->each(sub { print $_[0], ' is ', $_[1], "\n" });
694
695       Or:
696
697         my %hash = ( foo => 10, bar => 20, baz => 30, quux => 40 );
698         %hash->each(sub { print $_[0], ' is ', $_[1], "\n" });
699
700       Unlike regular "each", this each will always iterate through the entire
701       hash.
702
703       Hash keys appear in random order that varies from run to run (this is
704       intentional, to avoid calculated attacks designed to trigger
705       algorithmic worst case scenario in "perl"'s hash tables).
706
707       You can get a sorted "foreach" by combining "keys", "sort", and
708       "foreach":
709
710          %hash->keys->sort->foreach(sub {
711             print $_[0], ' is ', $hash{$_[0]}, "\n";
712          });
713
714       lock_keys
715
716           %hash->lock_keys;
717
718       Works as "lock_keys" in Hash::Util.  No more keys may be added to the
719       hash.
720
721       slice
722
723       Takes a list of hash keys and returns the corresponding values e.g.
724
725         my %hash = (
726             one   => 'two',
727             three => 'four',
728             five  => 'six'
729         );
730
731         print %hash->slice(qw(one five))->join(' and '); # prints "two and six"
732
733       flip
734
735       Exchanges values for keys in a hash:
736
737           my %things = ( foo => 1, bar => 2, baz => 5 );
738           my %flipped = %things->flip; # { 1 => foo, 2 => bar, 5 => baz }
739
740       If there is more than one occurrence of a certain value, any one of the
741       keys may end up as the value.  This is because of the random ordering
742       of hash keys.
743
744           # Could be { 1 => foo }, { 1 => bar }, or { 1 => baz }
745           { foo => 1, bar => 1, baz => 1 }->flip;
746
747       Because references cannot usefully be keys, it will not work where the
748       values are references.
749
750           { foo => [ 'bar', 'baz' ] }->flip; # dies
751
752       flatten
753
754           my %hash = $hash_ref->flatten;
755
756       Dereferences a hash reference.
757
758       Code Methods
759
760       Methods which work on code references.
761
762       These are simple wrappers around the Perl core functions.  bless, ref,
763
764       Due to Perl's precedence rules, some autoboxed literals may need to be
765       parenthesized.  For instance, this works:
766
767         my $curried = sub { ... }->curry();
768
769       This does not:
770
771         my $curried = \&foo->curry();
772
773       The solution is to wrap the reference in parentheses:
774
775         my $curried = (\&foo)->curry();
776
777       curry
778
779           my $curried_code = $code->curry(5);
780
781       Currying takes a code reference and provides the same code, but with
782       the first argument filled in.
783
784           my $greet_world = sub {
785               my($greeting, $place) = @_;
786               return "$greeting, $place!";
787           };
788           print $greet_world->("Hello", "world");  # "Hello, world!"
789
790           my $howdy_world = $greet_world->curry("Howdy");
791           print $howdy_world->("Texas");           # "Howdy, Texas!"
792
793   What's Missing?
794       •   File and socket operations are already implemented in an object-
795           oriented fashion care of IO::Handle, IO::Socket::INET, and IO::Any.
796
797       •   Functions listed in the perlfunc headings
798
799           •   "System V interprocess communication functions",
800
801           •   "Fetching user and group info",
802
803           •   "Fetching network info",
804
805           •   "Keywords related to perl modules",
806
807           •   "Functions for processes and process groups",
808
809           •   "Keywords related to scoping",
810
811           •   "Time-related functions",
812
813           •   "Keywords related to the control flow of your perl program",
814
815           •   "Functions for filehandles, files, or directories",
816
817           •   "Input and output functions".
818
819       •   (Most) binary operators
820
821       These things are likely implemented in an object oriented fashion by
822       other CPAN modules, are keywords and not functions, take no arguments,
823       or don't make sense as part of the string, number, array, hash, or code
824       API.
825
826   Autoboxing
827       This section quotes four pages from the manuscript of Perl 6 Now: The
828       Core Ideas Illustrated with Perl 5 by Scott Walters. The text appears
829       in the book starting at page 248. This copy lacks the benefit of
830       copyedit - the finished product is of higher quality.
831
832       A box is an object that contains a primitive variable.  Boxes are used
833       to endow primitive types with the capabilities of objects which
834       essential in strongly typed languages but never strictly required in
835       Perl.  Programmers might write something like "my $number =
836       Int->new(5)".  This is manual boxing.  To autobox is to convert a
837       simple type into an object type automatically, or only conceptually.
838       This is done by the language.
839
840       autoboxing makes a language look to programmers as if everything is an
841       object while the interpreter is free to implement data storage however
842       it pleases.  Autoboxing is really making simple types such as numbers,
843       strings, and arrays appear to be objects.
844
845       "int", "num", "bit", "str", and other types with lower case names, are
846       primitives.  They're fast to operate on, and require no more memory to
847       store than the data held strictly requires.  "Int", "Num", "Bit",
848       "Str", and other types with an initial capital letter, are objects.
849       These may be subclassed (inherited from) and accept traits, among other
850       things.  These objects are provided by the system for the sole purpose
851       of representing primitive types as objects, though this has many
852       ancillary benefits such as making "is" and "has" work.  Perl provides
853       "Int" to encapsulate an "int", "Num" to encapsulate a "num", "Bit" to
854       encapsulate a "bit", and so on.  As Perl's implementations of hashes
855       and dynamically expandable arrays store any type, not just objects,
856       Perl programmers almost never are required to box primitive types in
857       objects.  Perl's power makes this feature less essential than it is in
858       other languages.
859
860       autoboxing makes primitive objects and they're boxed versions
861       equivalent.  An "int" may be used as an "Int" with no constructor call,
862       no passing, nothing.  This applies to constants too, not just
863       variables.  This is a more Perl 6 way of doing things.
864
865         # Perl 6 - autoboxing associates classes with primitives types:
866
867         print 4.sqrt, "\n";
868
869         print [ 1 .. 20 ].elems, "\n";
870
871       The language is free to implement data storage however it wishes but
872       the programmer sees the variables as objects.
873
874       Expressions using autoboxing read somewhat like Latin suffixes.  In the
875       autoboxing mind-set, you might not say that something is "made more
876       mnemonic", but has been "mnemonicified".
877
878       Autoboxing may be mixed with normal function calls.  In the case where
879       the methods are available as functions and the functions are available
880       as methods, it is only a matter of personal taste how the expression
881       should be written:
882
883         # Calling methods on numbers and strings, these three lines are equivalent
884         # Perl 6
885
886         print sqrt 4;
887         print 4.sqrt;
888         4.sqrt.print;
889
890       The first of these three equivalents assumes that a global sqrt()
891       function exists.  This first example would fail to operate if this
892       global function were removed and only a method in the "Num" package was
893       left.
894
895       Perl 5 had the beginnings of autoboxing with filehandles:
896
897         use IO::Handle;
898         open my $file, '<', 'file.txt' or die $!;
899         $file->read(my $data, -s $file);
900
901       Here, "read" is a method on a filehandle we opened but never blessed.
902       This lets us say things like "$file->print(...)" rather than the often
903       ambagious "print $file ...".
904
905       To many people, much of the time, it makes more conceptual sense as
906       well.
907
908       Reasons to Box Primitive Types
909
910       What good is all of this?
911
912       •   Makes conceptual sense to programmers used to object interfaces as
913           the way to perform options.
914
915       •   Alternative idiom. Doesn't require the programmer to write or read
916           expressions with complex precedence rules or strange operators.
917
918       •   Many times that parenthesis would otherwise have to span a large
919           expression, the expression may be rewritten such that the
920           parenthesis span only a few primitive types.
921
922       •   Code may often be written with fewer temporary variables.
923
924       •   Autoboxing provides the benefits of boxed types without the memory
925           bloat of actually using objects to represent primitives. Autoboxing
926           "fakes it".
927
928       •   Strings, numbers, arrays, hashes, and so on, each have their own
929           API.  Documentation for an "exists" method for arrays doesn't have
930           to explain how hashes are handled and vice versa.
931
932       •   Perl tries to accommodate the notion that the "subject" of a
933           statement should be the first thing on the line, and autoboxing
934           furthers this agenda.
935
936       Perl is an idiomatic language and this is an important idiom.
937
938       Subject First: An Aside
939
940       Perl's design philosophy promotes the idea that the language should be
941       flexible enough to allow programmers to place the subject of a
942       statement first.  For example, "die $! unless read $file, 60" looks
943       like the primary purpose of the statement is to "die".
944
945       While that might be the programmers primary goal, when it isn't, the
946       programmer can communicate his real primary intention to programmers by
947       reversing the order of clauses while keeping the exact same logic:
948       "read $file, 60 or die $!".
949
950       Autoboxing is another way of putting the subject first.
951
952       Nouns make good subjects, and in programming, variables, constants, and
953       object names are the nouns.  Function and method names are verbs.
954       "$noun->verb()" focuses the readers attention on the thing being acted
955       on rather than the action being performed.  Compare to $verb($noun).
956
957       Autoboxing and Method Results
958
959       Let's look at some examples of ways an expression could be written.
960
961         # Various ways to do the same thing:
962
963         print(reverse(sort(keys(%hash))));          # Perl 5 - pathological parenthetic
964         print reverse sort keys %hash;              # Perl 5 - no unneeded parenthesis
965
966         print(reverse(sort(%hash,keys))));          # Perl 6 - pathological
967         print reverse sort %hash.keys;              # Perl 6 - no unneeded parenthesis
968
969         %hash.keys ==> sort ==> reverse ==> print;  # Perl 6 - pipeline operator
970
971         %hash.keys.sort.reverse.print;              # Perl 6 - autobox
972
973         %hash->keys->sort->reverse->print;          # Perl 5 - autobox
974
975       This section deals with the last two of these equivalents.  These are
976       method calls
977
978         use autobox::Core;
979         use Perl6::Contexts;
980
981         my %hash = (foo => 'bar', baz => 'quux');
982
983         %hash->keys->sort->reverse->print;          # Perl 5 - autobox
984
985         # prints "foo baz"
986
987       Each method call returns an array reference, in this example.  Another
988       method call is immediately performed on this value.  This feeding of
989       the next method call with the result of the previous call is the common
990       mode of use of autoboxing.  Providing no other arguments to the method
991       calls, however, is not common.
992
993       "Perl6::Contexts" recognizes object context as provided by "->" and
994       coerces %hash and @array into references, suitable for use with
995       "autobox".  (Note that "autobox" also does this automatically as of
996       version 2.40.)
997
998       "autobox" associates primitive types, such as references of various
999       sorts, with classes.  "autobox::Core" throws into those classes methods
1000       wrapping Perl's built-in functions.  In the interest of full
1001       disclosure, "Perl6::Contexts" and "autobox::Core" are my creations.
1002
1003       Autobox to Simplify Expressions
1004
1005       One of my pet peeves in programming is parenthesis that span large
1006       expression.  It seems like about the time I'm getting ready to close
1007       the parenthesis I opened on the other side of the line, I realize that
1008       I've forgotten something, and I have to arrow back over or grab the
1009       mouse.
1010
1011       When the expression is too long to fit on a single line, it gets broken
1012       up, then I must decide how to indent it if it grows to 3 or more lines.
1013
1014         # Perl 5 - a somewhat complex expression
1015
1016         print join("\n", map { CGI::param($_) } @cgi_vars), "\n";
1017         # Perl 5 - again, using autobox:
1018
1019         @cgi_vars->map(sub { CGI::param($_[0]) })->join("\n")->concat("\n")->print;
1020
1021       The autoboxed version isn't shorter, but it reads from left to right,
1022       and the parenthesis from the join() don't span nearly as many
1023       characters.  The complex expression serving as the value being join()ed
1024       in the non-autoboxed version becomes, in the autoboxed version, a value
1025       to call the join() method on.
1026
1027       This "print" statement takes a list of CGI parameter names, reads the
1028       values for each parameter, joins them together with newlines, and
1029       prints them with a newline after the last one.
1030
1031       Pretending that this expression were much larger and it had to be
1032       broken to span several lines, or pretending that comments are to be
1033       placed after each part of the expression, you might reformat it as
1034       such:
1035
1036         @cgi_vars->map(sub { CGI::param($_[0]) })  # turn CGI arg names into values
1037                  ->join("\n")                      # join with newlines
1038                  ->concat("\n")                    # give it a trailing newline
1039                  ->print;                          # print them all out
1040
1041       Here ends the text quoted from the Perl 6 Now manuscript.
1042

BUGS

1044       Yes. Report them to the author, scott@slowass.net, or post them to
1045       GitHub's bug tracker at
1046       <https://github.com/scrottie/autobox-Core/issues>.
1047
1048       The API is not yet stable -- Perl 6-ish things and local extensions are
1049       still being renamed.
1050

HISTORY

1052       See the Changes file.
1053
1055       Copyright (C) 2009, 2010, 2011 by Scott Walters and various
1056       contributors listed (and unlisted) below.
1057
1058       This library is free software; you can redistribute it and/or modify it
1059       under the same terms as Perl itself, either Perl version 5.8.9 or, at
1060       your option, any later version of Perl 5 you may have available.
1061
1062       This library is distributed in the hope that it will be useful, but
1063       without any warranty; without even the implied warranty of
1064       merchantability or fitness for a particular purpose.
1065

SEE ALSO

1067       autobox
1068       Moose::Autobox
1069       Perl6::Contexts
1070       <http://github.com/gitpan/autobox-Core>
1071       IO::Any
1072       Perl 6: <http://dev.perl.org/perl6/apocalypse/>.
1073

AUTHORS

1075       Scott Walters, scott@slowass.net.
1076
1077       Tomasz Konojacki has been assisting with maint.
1078
1079       Jacinta Richardson improved documentation and tidied up the interface.
1080
1081       Michael Schwern and the perl5i contributors for tests, code, and
1082       feedback.
1083
1084       JJ contributed a "strip" method for scalars - thanks JJ!
1085
1086       Ricardo SIGNES contributed patches.
1087
1088       Thanks to Matt Spear, who contributed tests and definitions for numeric
1089       operations.
1090
1091       Mitchell N Charity reported a bug and sent a fix.
1092
1093       Thanks to chocolateboy for autobox and for the encouragement.
1094
1095       Thanks to Bruno Vecchi for bug fixes and many, many new tests going
1096       into version 0.8.
1097
1098       Thanks to <http://github.com/daxim> daxim/Lars DIECKOW pushing in fixes
1099       and patches from the RT queue along with fixes to build and additional
1100       doc examples.
1101
1102       Thanks to Johan Lindstrom for bug reports.
1103
1104       Thanks to everyone else who sent fixes or suggestions -- apologies if I
1105       failed to include you here!
1106
1107
1108
1109perl v5.36.0                      2023-01-20                  autobox::Core(3)
Impressum