forked from scrottie/autobox-Core
/
Core.pm
1906 lines (1283 loc) · 51.3 KB
/
Core.pm
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
package autobox::Core;
# TODO:
# o. Lars D implemented a times() method for scalars but there is no doc or comment and I don't see the point; commented it out for now.
# (scrottie)
# o. @array->random ?
# o. "5->times(sub { print "hi\n"}); # XXX likely to change but it's in the code so bloody doc it so I have incentive to rethink it".
# well? do we want this? (scrottie)
# o. kill head() and tail() -- does it really make sense to try to emulate linked lists with Perl arrays? cute idea, but, uh. (scrottie)
# o. "There's currently no counterpart to the C<< \ >> operator" -- but should we back away from trying to name operators and
# only do built-in functions? (scrottie)
# o. I no longer think that center() belongs here; plenty of modules offer text formatting (scrottie)
# o. don't overlap with autobox::List::Util. or else do. but decide.
# o. make jive with MooseX::Autobox or whatever it is
# v/ regenerate README
# o. steal perl5i's docs too
# o. IO::Any?
# o. "appending the user-supplied arguments allows autobox::Core options to be overridden" -- document this if we haven't already
# v/ more Hash::Util methods?
# o. "If this goes over well, I'll make L<Langauge::Functional> a dependency and expose its function as methods on the correct data types. Or maybe I will do this anyway."
# ... maybe there should be filter, fold, reduce, etc methods
# o. support 'my IO::Handle $io; $io->open('<', $fn);'. undef values belonging to
# SVs having associated types should dispatch to that class. of course, just using
# core, this could be made to work too -- open() is a built-in, after all. the
# autobox::Core::open would have to know how to handle $_[0] being undef and
# assigning the open'ed handle into $_[0].
#
# from http://search.cpan.org/~miyagawa/PSGI-1.03/PSGI/FAQ.pod:
#
# body.each { |buf| request.write(buf) }
#
#would just magically work whether body is an Array, FileIO object or an object that implements iterators. Perl doesn't have such a beautiful thing in the language unless autobox is loaded. PSGI should not make autobox as a requirement, so we only support a simple array ref or file handle.
#
# ... perl5i should unify interfaces to IO handles, arrays, hashes, objects, etc as much as possible.
use 5.008;
use strict;
use warnings;
our $VERSION = '1.21';
use base 'autobox';
use B;
# appending the user-supplied arguments allows autobox::Core options to be overridden
# or extended in the same statement e.g.
#
# use autobox::Core UNDEF => 'MyUndef'; # also autobox undef
# use autobox::Core CODE => undef; # don't autobox CODE refs
# use autobox::Core UNIVERSAL => 'Data::Dumper'; # enable a Dumper() method for all types
sub import {
shift->SUPER::import(DEFAULT => 'autobox::Core::', @_);
}
=encoding UTF-8
=head1 NAME
autobox::Core - Core functions exposed as methods in primitive types
=head1 SYNOPSIS
use autobox::Core;
"Hello, World\n"->uc->print;
=head1 DESCRIPTION
The L<autobox> module lets you call methods on primitive datatypes such as
scalars and arrays.
L<autobox::CORE> defines methods for core operations such as C<join>, C<print>,
most everything in L<perlfunc>, some things from L<Scalar::Util> and
L<List::Util>, and some Perl 5 versions of methods taken from Perl 6.
These methods expose as methods the built-in functions for minipulating
numbers, strings, arrays, hashes, and code references.
It can be handy to use built-in functions as methods to avoid
messy dereferencing syntaxes and parentheses pile ups.
F<autobox::Core> is what you'd call a I<stub> module. It is mostly glue, presenting
existing functions with a new interface. Most of the methods read like
C<< sub hex { hex($_[0]) } >>.
Besides built-ins that operate on hashes, arrays, scalars, and code references,
some Perl 6-ish things were thrown in, and some keyword like C<foreach> have
been turned into methods.
=head2 What's Implemented?
All of the functions listed in L<perldoc> under the headings:
"Functions for real @ARRAYs",
"Functions for real %HASHes",
"Functions for list data",
and "Functions for SCALARs or strings", plus a few taken from other sections
and documented below.
Methods from L<Scalar::Util> and L<List::Util> were thrown in.
Some things expected in Perl 6, such as C<last> (C<last_idx>), C<elems>, and C<curry>, have been thrown in.
C<flatten> explicitly flattens an array.
Functions such as C<add> have been defined for numeric operations.
Here's a small sample:
print [10, 20, 30, 40, 50]->pop, "\n";
print [10, 20, 30, 40, 50]->shift, "\n";
my $arrref = [10, 20, 30];
my $lala;
$lala = "Lalalalala\n"; print "chomp: ", $lala->chomp, ' ', $lala, "\n";
$lala = "Lalalalala\n"; print "lcfirst: ", $lala->lcfirst, ' ', $lala, "\n";
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";
Of the built-in stuff, only a few stragglers such as C<srand> were excluded.
=head3 String Methods
String methods are of the form C<< my $return = $string->method(@args) >>.
Some will act on the C<$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 L<split> and L<m>,
must take it in the form of a compiled regex (C<qr//>). Any modifiers
can be attached to the C<qr> normally.
These built in functions are implemented for scalars, they work just like normal:
L<chomp|perlfunc/chomp>, L<chop|perlfunc/chop>,L<chr|perlfunc/chr>
L<crypt|perlfunc/crypt>, L<index|perlfunc/index>, L<lc|perlfunc/lc>
L<lcfirst|perlfunc/lcfirst>, L<length|perlfunc/length>, L<ord|perlfunc/ord>,
L<pack|perlfunc/pack>, L<reverse|perlfunc/reverse>, L<rindex|perlfunc/rindex>,
L<sprintf|perlfunc/sprintf>, L<substr|perlfunc/substr>, L<uc|perlfunc/uc>
L<ucfirst|perlfunc/ucfirst>, L<unpack|perlfunc/unpack>, L<quotemeta|perlfunc/quotemeta>,
L<vec|perlfunc/vec>, L<undef|perlfunc/undef>, L<m|perlfunc/m>, L<nm|perlfunc/nm>,
L<s|perlfunc/s>, L<split|perlfunc/split>, L<system|perlfunc/system>, L<eval|perlfunc/eval>.
=head4 cmp
my $cmp = $a->cmp($b);
Compare two strings, just like the C<cmp> operator.
If $a is greater, it returns 1. If $b is greater, it returns -1.
If they're equal, it returns 0.
=head4 eq
C<eq> returns true if the values are equal strings.
"foo"->eq("bar"); #false
"foo"->eq("foo"); #true
=head4 ne
=head4 ge
=head4 gt
=head4 le
=head4 lt
The string comparison operators of the same name. They're called like
L<eq>.
=head4 concat
Corresponds to the C<.> operator used to join two strings.
=head4 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 C<trim>.
=head4 trim
Removes whitespace from the beginning and end of a string. C<trim>
can also remove specific characters from the beginning and the end of
string.
' hello'->trim; # testme
'--> hello <--'->trim("-><"); # testme
' --> hello <--'->trim("-><"); # --> testme
=head4 ltrim
Just like L<trim> but it only trims the left side (start) of the string.
=head4 rtrim
Just like L<trim> but it only trims the right side (end) of the string.
=head4 split
my @split_string = $string->split(qr/.../);
A wrapper around L<split|perlfunc/split>. It takes the regular
expression as a compiled 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.
=head4 title_case
C<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
=head4 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.
C<$character> defaults to " ".
say "Hello"->center(10); # " Hello ";
say "Hello"->center(10, '-'); # "---Hello--";
C<center()> will never truncate C<$string>. If $length is less
than C<< $string->length >> it will just return C<$string>.
say "Hello"->center(4); # "Hello";
=head4 backtick
my $output = $string->backtick;
Runs $string as a command just like C<`$string`>.
=head4 nm
"Negative match". Corresponds to C<< !~ >>.
=head4 m
my $matches = $foo->m(qr/bar/);
Works the same as C<< m// >>, but the regex must be passed in as a C<qr//>.
C<m> returns an array reference so that things such as C<map> and
C<grep> may be called on the result.
my ($street_number, $street_name, $apartment_number) =
"1234 Robin Drive #101"->m( qr{(\d+) (.*)(?: #(\d+))?} )->elements;
print "$street_number $street_name $apartment_number\n";
=head4 s
Works the same as C<< s/// >>.
=head4 undef
$string->undef;
Assigns C<undef> to the C<$string>.
=head4 defined
my $is_defined = $string->defined;
C<defined> tests whether a value is defined (not C<undef>).
=head4 rpt
my $repeated_string = $string->rpt($n);
Like the C<x> operator, repeats a string C<$n> times.
print 1->rpt(5); # 11111
=head3 I/O Methods
These are methods having to do with input and ouptut, not filehandles.
=head4 print
$string->print;
@array->print;
Prints a string or a list of strings. Returns true if successful.
=head4 say
Like L<print>, but implicitly appends a newline to the end.
=head3 Number Related Methods
Methods related to numbers.
The basic built in functions which operate as normal :
L<abs|perlfunc/abs>, L<atan2|perlfunc/atan2>, L<cos|perlfunc/cos>, L<exp|perlfunc/exp>,
L<int|perlfunc/int>, L<log|perlfunc/log>, L<oct|perlfunc/oct>, L<hex|perlfunc/hex>,
L<rand|perlfunc/rand>, L<sin|perlfunc/sin>, and L<sqrt|perlfunc/sqrt>.
Operators were given names as follows:
=head4 add
Corresponds to C<+>.
=head4 and
Corresponds to C<&&> .
=head4 band
Corresponds to C<&> that is short-circuit and.
=head4 bor
Corresponds to C<|> that is short-circuit or.
=head4 bxor
Corresponds to C<^> that is short-circuit xor.
=head4 dec
C<dec> returns the decimal part of a number.
=head4 div
C<div> returns the quotient of division.
=head4 flip
C<flip> corresponds to C<~> which is the binary (rather than boolean) "not".
=head4 inc
C<inc> corresponds to C<++>.
=head4 lshift
C<lshift> corresponds to C<< << >>.
=head4 mod
C<mod> corresponds to C<%>.
=head4 mult
C<mult> corresponds to C<*>.
=head4 mcmp
C<mcmp> compares two numbers and returns 0,1,-1 depending upon the type of input.
1->mcmp(5); # < 0
5->mcmp(5); # = 0
6->mcmp(5); # > 0
"M" for "math".
=head4 mge
The C<< >= >> operator.
=head4 meq
The C<==> operator.
=head4 mgt
The C<< > >> operator.
=head4 mle
The C<< <= >> operator.
=head4 mlt
The C<< < >> operator.
=head4 mne
The C<!=> operator.
=head4 not
C<not> corresponds to C<!>.
=head4 or
C<or> corresponds to C<||>.
=head4 pow
my $result = $number->pow($expontent);
C<pow> returns $number raised to the power of the $exponent.
print 2->pow(8); # 256
=head4 rshift
C<rshift> corresponds to C<<< >> >>>.
=head4 sub
C<sub> corresponds to C<->.
=head4 xor
C<xor> corresponds to <^>.
=head4 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
=head4 is_positive
$is_positive = $thing->is_positive;
Returns true if $thing is a positive number.
C<0> is not positive.
=head4 is_negative
$is_negative = $thing->is_negative;
Returns true if $thing is a negative number.
C<0> is not negative.
=head4 is_integer
$is_an_integer = $thing->is_integer;
Returns true if $thing is an integer.
12->is_integer; # true
12.34->is_integer; # false
=head4 is_int
A synonym for is_integer.
=head4 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
=head3 Reference Related Methods
The following core functions are implemented.
L<tie|perlfunc/tie>, L<tied|perlfunc/tied>, L<ref|perlfunc/ref>,
L<bless|perlfunc/bless>, L<vec|perlfunc/vec>.
C<tie>, C<tied>, and C<undef> don't work on code references.
=head3 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; # "1\n";
These built-in functions are defined as methods:
L<pop|perlfunc/pop>, L<push|perlfunc/push>, L<shift|perlfunc/shift>,
L<unshift|perlfunc/unshift>, L<delete|perlfunc/delete>,
L<undef|perlfunc/undef>, L<exists|perlfunc/exists>,
L<bless|perlfunc/bless>, L<tie|perlfunc/tie>, L<tied|perlfunc/tied>, L<ref|perlfunc/ref>,
L<grep|perlfunc/grep>, L<map|perlfunc/map>, L<join|perlfunc/join>, L<reverse|perlfunc/reverse>,
and L<sort|perlfunc/sort>, L<each|perlfunc/each>,
=head4 vdelete
Deletes a specified value from the array.
$a = 1->to(10);
$a->vdelete(3); # deletes 3
=head4 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
=head4 first
Returns the first element of an array for which a callback returns true:
$arr->first(sub { /5/ });
=head4 max
Returns the largest numerical value in the array.
$a = 1->to(10);
$a->max; # 10
=head4 min
Returns the smallest numerical value in the array.
$a = 1->to(10);
$a->min; # 1
=head4 mean
Returns the mean of elements of an array.
$a = 1->to(10);
$a->mean; # 55/10
=head4 var
Returns the variance of the elements of an array.
$a = 1->to(10);
$a->var; # 33/4
=head4 svar
Returns the standars variance.
$a = 1->to(10);
$a->svar; # 55/6
=head4 at
Returns the element at a specified index. This function does not modify the
original array.
$a = 1->to(10);
$a->at(2); # 3
=head4 size
=head4 elems
=head4 length
All return the number of elements in an array.
my @array = qw(foo bar baz);
@array->size; # 3
=head4 elements
=head4 flatten
my @copy_of_array = $array->flatten;
Returns the elements of an array ref as an array.
This is the same as C<< @{$array} >>.
Arrays can be iterated on using C<for> and C<foreach>. Both take a code
reference as the body of the for statement.
=head4 foreach
@array->foreach(\&code);
Calls C<&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
=head4 for
@array->for(\&code);
Like L<foreach>, but C<&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";
});
=head4 sum
my $sum = @array->sum;
Adds together all the elements of the array.
=head4 count
Returns the number of elements in array that are C<eq> to a specified value:
my @array = qw/one two two three three three/;
my $num = @array->count('three'); # returns 3
=head4 to, upto, downto
C<to>, C<upto>, and C<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 C<..> operator.
B<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
=head4 head
Returns the first element from C<@list>.
my $first = @list->head;
=head4 tail
Returns all but the first element from C<@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 C<$n>
elements:
@rest = @list->tail(2); # [ 'baz', 'quux' ]
=head4 slice
Returns a list containing the elements from C<@list> at the indices
C<@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);
=head4 range
C<range> returns a list containing the elements from C<@list> with indices
ranging from C<$lower_idx> to C<$upper_idx>. It returns an array reference
in scalar context.
my @sublist = @list->range( $lower_idx, $upper_idx );
=head4 last_index
my $index = @array->last_index;
Called with no arguments, it corresponds to C<$#array> giving the
highest index of the array.
my $index = @array->last_index(qr/.../);
Returns the highest index matching the given regular expression.
my $index = @array->last_index(\&filter);
Returns the highest index for 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
=head4 first_index
Works just like L<last_index> but it will return the I<first> matching index.
my $first_index = @array->first_index; # 0
my @things = qw(pear poll potato tomato);
my $last_p = @things->first_index(qr/^t/); # 3
=head4 at
my $value = $array->at($index);
Equivalent to C<< $array->[$index] >>.
=head3 Hash Methods
Hash methods work on both hashes and hash references.
The built in functions work as normal:
L<delete|perlfunc/delete>, L<exists|perlfunc/exists>, L<keys|perlfunc/keys>,
L<values||perlfunc/values>, L<bless|perlfunc/bless>, L<tie|perlfunc/tie>,
L<tied|perlfunc/tied>, L<ref|perlfunc/ref>, L<undef|perlfunc/undef>,
are implemented.
=head4 at
=head4 get
my @values = %hash->get(@keys);
Returns the @values of @keys.
=head4 put
%hash->push(%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)
=head4 set
Synonym for L<put>
=head4 each
Like C<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 C<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 C<perl>'s hash tables).
You can get a sorted C<foreach> by combining C<keys>, C<sort>, and C<foreach>:
%hash->keys->sort->foreach(sub {
print $_[0], ' is ', $hash{$_[0]}, "\n";
});
=head4 lock_keys
%hash->lock_keys;
Works as L<Hash::Util/lock_keys>. No more keys may be added to the hash.
=head4 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"
=head4 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 occurence 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 hash references cannot usefully be keys, it will not work on
nested hashes.
{ foo => [ 'bar', 'baz' ] }->flip; # dies
=head4 flatten
my %hash = $hash_ref->flatten;
Dereferences a hash reference.
=head3 Code Methods
Methods which work on code references.
These are simple wrappers around the Perl core fnctions.
L<bless|perlfunc/bless>, L<ref|perlfunc/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();
=head4 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!"
=head4 map
my @mapped_array = $code->map(@array);
my $mapped_array = $code->map(@array);
Like L<map|perlfunc/map>. Runs each element of @array through $code
and returns the transformed elements.
sub { my $t = $_[0]; $t =~ tr/a-z/zyxwvutsrqponmlkjihgfedcba/; $t }->map(
"Black", "crow", "flies", "at", "midnight"
)->say;
=head2 What's Missing?
File and socket operations are already implemented in an object-oriented fashion
care of L<IO::Handle>, L<IO::Socket::INET>, and L<IO::Any>.
Functions listed in the L<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",
and
"Input and output functions".
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.
C<srand> because you probably shouldn't be using it.
=head2 Autoboxing
I<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 I<box> is an object that contains a primitive variable.
Boxes are used to endow primitive types with the capabilities of objects.
This is essential in strongly typed languages but never strictly required in Perl.
Programmers might write something like C<< my $number = Int->new(5) >>.
This is manual boxing.
To I<autobox> is to convert a simple type into an object type automatically, or only conceptually.
This is done by the language.
It 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.
C<int>, C<num>, C<bit>, C<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.
C<Int>, C<Num>, C<Bit>, C<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 C<is> and C<has> work.
Perl provides C<Int> to encapsulate an C<int>, C<Num> to encapsulate a C<num>, C<Bit> to encapsulate a C<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.
X<autobox>ing makes primitive objects and they're boxed versions equivalent.
An C<int> may be used as an C<Int> with no constructor call, no passing, nothing.
This applies to constants too, not just variables:
# Perl 6 - autoboxing associates classes with primitives types:
print 4.sqrt, "\n";
This is perfectly valid Perl 6.
All of this applies to hashes and arrays, as well:
# Perl 6 - autoboxing associates classes with primitive types:
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 C<sqrt()> function exists.
This first example would fail to operate if this global function were removed and only
a method in the C<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, C<read> is a method on a filehandle we opened but I<never blessed>.
This lets us say things like C<< $file->print(...) >> rather than the often ambagious
C<< print $file ... >>.
To many people, much of the time, it makes more conceptual sense as well.
=head3 Reasons to Box Primitive Types
What good is all of this?
=over 1
=item Makes conceptual sense to programmers used to object interfaces as I<the> way
to perform options.
=item Alternative idiom. Doesn't require the programmer
to write or read expressions with complex precedence rules or strange operators.
=item 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.