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