autobox-Core-1.33004075500017500000012000000000001302533716600130475ustar00scottusersautobox-Core-1.33/t004075500017500000012000000000001302533716500133115ustar00scottusersautobox-Core-1.33/t/split.t010064400017500000012000000003651134511145200147010ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; is_deeply ["hi there"->split(qr/ */)], [qw(h i t h e r e)]; my $arrayref = "hi there"->split(qr/ */); is ref $arrayref, 'ARRAY', "Returns arrayref in scalar context"; autobox-Core-1.33/t/rindex.t010064400017500000012000000003651134511145200150370ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my $string = "I like pie pie"; my $substr = "pie"; is $string->rindex($substr), rindex($string, $substr); is $string->rindex($substr, 12), rindex($string, $substr, 12); autobox-Core-1.33/t/tail.t010064400017500001750000000007501165343654500145210ustar00scottscott#!/usr/bin/env perl use strict; use warnings; use Test::More tests => 7; use autobox::Core; my @array = qw(foo bar baz); ok @array->tail; is_deeply [@array->tail], ['bar', 'baz']; is_deeply [@array->tail(1)], ['baz']; is_deeply [@array->tail(2)], ['bar', 'baz']; is_deeply [@array->tail(3)], ['foo', 'bar', 'baz']; my @tail = @array->tail; is scalar @tail, 2, "Returns a list in list context"; my $tail = @array->tail; is ref $tail, 'ARRAY', "Returns an arrayref in scalar context"; autobox-Core-1.33/t/concat.t010064400017500000012000000001701135075462300150200ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; is 'foo'->concat(qw(bar quux)), 'foobarquux'; autobox-Core-1.33/t/ucfirst.t010064400017500000012000000002271134511145200152220ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my $string = "this is a string"; is $string->ucfirst, "This is a string"; autobox-Core-1.33/t/s.t010064400017500000012000000006721264135772400140270ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my $string = 'HELLO'; $string->s('^HE', 'Hu'); is $string, 'HuLLO'; ok $string->s(qr/LO/, '10') eq 'HuL10'; # using ok() instead of is() to test Want picking up on scalar context ok ! $string->s(qr/LO/, '10'); # testing Want picking up on boolean context ok ! ! $string->s(qr/10/, 'lo'); # testing Want picking up on boolean context autobox-Core-1.33/t/say.t010064400017500000012000000010401134511145200143310ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my $message = "This is an important message"; my @array = qw(this is an important message); SKIP: { my $has_test_output = eval { require Test::Output }; skip "Don't have Test::Output", 1, if not $has_test_output; Test::Output::stdout_is( sub { $message->say }, $message . "\n" ); Test::Output::stdout_is( sub { @array->say }, "@array\n" ); } # We need at least one test so that Test::Harness doesn't complain in # case we had to skip above ok 1; autobox-Core-1.33/t/pack.t010064400017500000012000000005451134511304500144640ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; SKIP: { # XXX this and pack.t could use a counterpart that works on 5.8 but this is so utterly non-urgent -- sdw skip "Only for 5.10", 1, if $] < 5.010; is 'nN'->pack(42, 4711), pack('nN', 42, 4711); is '(sl)<'->pack(-42, 4711), pack('(sl)<', -42, 4711); }; ok(1); autobox-Core-1.33/t/uc.t010064400017500000012000000002221134511145200141450ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my $string = "this is a string"; is $string->uc, "THIS IS A STRING"; autobox-Core-1.33/t/substr.t010064400017500000012000000006151134511145200150660ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my $s = "The black cat climbed the green tree"; my $color = $s->substr(4, 5); is $color, 'black'; my $middle = $s->substr(4, -11); is $middle, 'black cat climbed the'; my $end = $s->substr(14); is $end, 'climbed the green tree'; my $tail = $s->substr(-4); is $tail, 'tree'; my $z = $s->substr(-4, 2); is $z, 'tr'; autobox-Core-1.33/t/crypt.t010064400017500001750000000004721264134615200147220ustar00scottscottuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; use Config; SKIP: { skip("crypt not defined on this system", 1) unless $Config{d_crypt}; skip("crypt redefined to use a different algorithm", 1) if $Config{osname} eq 'openbsd'; is 'PLAINTEXT'->crypt('SALT'), 'SAPH9ylAEPe62'; } autobox-Core-1.33/t/sort.t010064400017500000012000000005611134511145200145330ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my @array = qw(foo bar baz); my @returned = @array->sort; is_deeply \@returned, [qw(bar baz foo)]; @returned = @array->sort(sub { $_[1] cmp $_[0] }); is_deeply \@returned, [qw(foo baz bar)]; my $arrayref = @array->sort; is ref $arrayref, "ARRAY", "Returns an arrayref in scalar context"; autobox-Core-1.33/t/scalar.t010064400017500000012000000015241134410366500150170ustar00scottusers#!perl use Test::More 'no_plan'; use autobox::Core; is( "this is a test"->title_case, 'This Is A Test'); is( "this is a test"->lc->title_case, 'This Is A Test'); is( "thIS is a teST"->title_case, 'ThIS Is A TeST'); is( "thIS is a teST"->lc->title_case, 'This Is A Test'); is( ' testme'->ltrim, 'testme' ); is( ' testme'->rtrim, ' testme' ); is( ' testme'->trim, 'testme' ); is( 'testme '->ltrim, 'testme ' ); is( 'testme '->rtrim, 'testme' ); is( 'testme '->trim, 'testme' ); is( ' testme '->ltrim, 'testme ' ); is( ' testme '->rtrim, ' testme' ); is( ' testme '->trim, 'testme' ); is( '--> testme <--'->ltrim("-><"), ' testme <--' ); is( '--> testme <--'->rtrim("-><"), '--> testme ' ); is( '--> testme <--'->trim("-><"), ' testme ' ); is( ' --> testme <--'->trim("-><"), ' --> testme ' ); autobox-Core-1.33/t/elems.t010064400017500000012000000001761134511145200146530ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my @array = qw(foo bar baz); is @array->elems, 3; autobox-Core-1.33/t/first_index.t010064400017500001750000000003401165343654500161010ustar00scottscott#!/usr/bin/env perl use autobox::Core; use Test::More tests => 3; my @numbers = ( 1 .. 10 ); is( @numbers->first_index, 0 ); is( @numbers->first_index( sub { $_[0] > 9 } ), 9 ); is( @numbers->first_index( qr/^2/ ), 1 ); autobox-Core-1.33/t/unshift.t010064400017500000012000000006451134511145200152270ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my @array = qw(foo bar); my @returned = @array->unshift('baz'); is_deeply \@array, [qw(baz foo bar)]; is_deeply \@returned, [qw(baz foo bar)]; my $arrayref = @array->unshift('baz'); is ref $arrayref, 'ARRAY', "Returns arrayref in scalar context"; my $array = [qw(foo bar)]; $array->unshift('baz'); is_deeply $array, [qw(baz foo bar)]; autobox-Core-1.33/t/last_index.t010064400017500001750000000003351165343654500157210ustar00scottscott#!/usr/bin/env perl use autobox::Core; use Test::More tests => 3; my @numbers = ( 1 .. 10 ); is( @numbers->last_index, 9 ); is( @numbers->last_index( sub { $_[0] > 2 } ), 9 ); is( @numbers->last_index( qr/^1/ ), 9 ); autobox-Core-1.33/t/each.t010064400017500001750000000012511165343654500144650ustar00scottscottuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my %hash = ( foo => 1, bar => 2, baz => 3 ); my @glued; %hash->each( sub { push @glued, $_[0] . $_[1] } ); is_deeply [ sort @glued ], [ qw(bar2 baz3 foo1) ]; my @array = values %hash; my @added; @array->each( sub { push @added, $_[0] + 1 } ); is_deeply [ sort @added ], [ qw(2 3 4) ]; # Ensure each() always iterates through the whole hash { my %want = (foo => 23, bar => 42, baz => 99, biff => 66); # Call each once on %want to start the iterator attached to %want my($k,$v) = each %want; my %have; %want->each( sub { $have{$_[0]} = $_[1] } ); is_deeply \%have, \%want; } autobox-Core-1.33/t/size.t010064400017500000012000000001751134511145200145170ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my @array = qw(foo bar baz); is @array->size, 3; autobox-Core-1.33/t/pop.t010064400017500000012000000002331134511145200143360ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my @array = qw(foo bar); is @array->pop, 'bar'; is_deeply \@array, [qw(foo)]; autobox-Core-1.33/t/array-slice.t010064400017500001750000000006451165343654500160060ustar00scottscott#!/usr/bin/env perl use strict; use warnings; use Test::More tests => 5; use autobox::Core; my @array = qw(foo bar baz); ok @array->slice(0); is_deeply [@array->slice(0)], ['foo']; is_deeply [@array->slice(0,2)], ['foo', 'baz']; my @slice = @array->slice(0,1); is scalar @slice, 2, "Returns an array in list context"; my $slice = @array->slice(0,1); is ref $slice, 'ARRAY', "Returns an arrayref in scalar context"; autobox-Core-1.33/t/shift.t010064400017500000012000000002351134511145200146570ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my @array = qw(foo bar); is @array->shift, 'foo'; is_deeply \@array, [qw(bar)]; autobox-Core-1.33/t/keys.t010064400017500000012000000004171134511145200145170ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my %hash = ( foo => 1, bar => 2, baz => 3 ); is_deeply [ sort %hash->keys ], [ qw( bar baz foo ) ]; my $arrayref = %hash->keys; is ref $arrayref, 'ARRAY', "Returns arrayref in scalar context"; autobox-Core-1.33/t/quotemeta.t010064400017500000012000000002101135075462300155500ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; is 'so (many [pairs])'->quotemeta, 'so\ \(many\ \[pairs\]\)'; autobox-Core-1.33/t/flip.t010064400017500001750000000004771215117335600145200ustar00scottscott#!/usr/bin/env perl use Test::More tests => 2; use autobox::Core; my %hash = ( 1 => 'foo', 3 => 'bar' ); my $f; is_deeply( $f = %hash->flip, { foo => 1, bar => 3 } ); my %f = %hash->flip; is_deeply( \%f, { foo => 1, bar => 3 }, "Returns hash in list context" ); my %nested = ( 1 => { foo => 'bar' }, 2 => 'bar' ); autobox-Core-1.33/t/ref.t010064400017500000012000000010201134511145200143070ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my %struct = ( ARRAY => [ 'foo' ], HASH => { 'foo' => 1 }, CODE => sub { 'foo' }, ); foreach my $reftype ( keys %struct ) { is $struct{$reftype}->ref, $reftype; } TODO: { todo_skip "Make it work for Regexp, Scalar and Glob", 3; my %todo = ( Regexp => qr/foo/, SCALAR => \'foo', GLOB => \*STDIN, ); foreach my $reftype ( keys %todo ) { is $todo{$reftype}->ref, $reftype; } } autobox-Core-1.33/t/slice.t010064400017500000012000000005531135050255200146450ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my $h = {a => 1, b => 2, c => 3}; my %h = %$h; my @slice = $h->slice(qw(a c)); is_deeply(\@slice, [ 1, 3 ]); my $slice = $h->slice(qw(b c)); is_deeply($slice, [ 2, 3 ]); @slice = %h->slice(qw(a c)); is_deeply(\@slice, [ 1, 3 ]); $slice = %h->slice(qw(b c)); is_deeply($slice, [ 2, 3 ]); autobox-Core-1.33/t/map.t010064400017500001750000000004671177446777100143630ustar00scottscottuse Test::More; use strict; use warnings; use autobox::Core; { my @array = qw(1 2 3); my @added = @array->map(sub { ++$_ }); is_deeply \@added, [qw(2 3 4)]; my $arrayref = @array->map( sub { 'foo' } ); is ref $arrayref, 'ARRAY', "Returns arrayref in scalar context"; } done_testing; autobox-Core-1.33/t/bless.t010064400017500000012000000011401134511145200146460ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my %struct = ( ARRAY => [ 'foo' ], HASH => { 'foo' => 1 }, CODE => sub { 'foo' }, ); foreach my $reftype ( keys %struct ) { $struct{$reftype}->bless("Object"); is ref $struct{$reftype}, "Object"; } TODO: { todo_skip "Make it work for Regexp, Scalar and Glob", 3; my %todo = ( Regexp => qr/foo/, SCALAR => \'foo', GLOB => \*STDIN, ); foreach my $reftype ( keys %todo ) { $todo{$reftype}->bless("Object"); is ref $todo{$reftype}, "Object"; } } autobox-Core-1.33/t/chr.t010064400017500000012000000001401134511145200143110ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; is 65->chr, chr(65); autobox-Core-1.33/t/reverse.t010064400017500001750000000010501165343654500152350ustar00scottscottuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; # https://github.com/schwern/perl5i/issues/182 my $scalar = 'foo'; my($reverse) = $scalar->reverse; # list context is $reverse, 'oof', 'reverse in list context reverses the scalar'; is scalar $scalar->reverse, 'oof', 'reverse in scalar context reverses the scalar'; is "Hello"->reverse, "olleH"; my @list = qw(foo bar baz); is_deeply [@list->reverse], [qw(baz bar foo)]; my $arrayref = @list->reverse; is ref $arrayref, "ARRAY", "returns an arrayref in scalar context"; autobox-Core-1.33/t/flatten.t010064400017500000012000000003261134511145200152000ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my @array = qw(foo bar baz); my @returned = @array->flatten; is_deeply \@returned, \@array; my $count = @array->flatten; is $count, 3; autobox-Core-1.33/t/center.t010064400017500001750000000017141165343654500150510ustar00scottscott#!/usr/bin/perl use autobox::Core; use Test::More tests => 25; my $hello = 'hello'; is( $hello->center(7), ' hello ', '->center() with even length has equal whitespace on both sides' ); is( $hello->center(7,'-'), '-hello-', '->center() with even length has equal whitespace on both sides' ); is( $hello->center(8), ' hello ', '->center() with odd length pads left' ); is( $hello->center(4), 'hello', '->center() with too-short length returns the string unmodified' ); is( $hello->center(0), 'hello', '->center(0)' ); is( $hello->center(-1), 'hello', '->center(-1)' ); is( "even"->center(6, "-"), '-even-', '->center(6, "-")' ); is( "even"->center(7, "-"), '--even-', '->center(7, "-")' ); is( "even"->center(0, "-"), 'even', '->center(0, "-")' ); # Test that center() always returns the correct length for my $size ($hello->length..20) { is( $hello->center($size)->length, $size, "center($size) returns that size" ); } autobox-Core-1.33/t/head.t010064400017500001750000000002441165343654500144670ustar00scottscott#!/usr/bin/env perl use strict; use warnings; use Test::More tests => 2; use autobox::Core; my @array = qw(foo bar baz); ok @array->head; is @array->head, 'foo'; autobox-Core-1.33/t/ord.t010064400017500000012000000001421134511145200143230ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; is 'A'->ord, ord('A'); autobox-Core-1.33/t/vec.t010064400017500000012000000004201134511145200143130ustar00scottusers use Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my $foo = ''; is $foo->vec(0, 32), vec($foo, 0, 32); # 0x5065726C, 'Perl' is $foo->vec(2, 16), vec($foo, 2, 16); # 0x5065, 'PerlPe' is $foo->vec(3, 16), vec($foo, 3, 16); # 0x726C, 'PerlPerl' autobox-Core-1.33/t/values.t010064400017500000012000000004161134511145200150420ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my %hash = ( foo => 1, bar => 2, baz => 3 ); is_deeply [ sort %hash->values ], [ qw( 1 2 3 ) ]; my $arrayref = %hash->values; is ref $arrayref, 'ARRAY', "Returns arrayref in scalar context"; autobox-Core-1.33/t/numeric.t010064400017500001750000000011451177446777100152420ustar00scottscottuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my $num = 0.5; my $e = 1E-10; cmp_ok( abs($num->abs - abs($num)), '<', $e ); cmp_ok( abs($num->cos - cos($num)), '<', $e ); cmp_ok( abs($num->exp - exp($num)), '<', $e ); cmp_ok( abs($num->int - int($num)), '<', $e ); cmp_ok( abs($num->log - log($num)), '<', $e ); cmp_ok( abs($num->oct - oct($num)), '<', $e ); cmp_ok( abs(05->hex - hex(05)), '<', $e ); cmp_ok( abs($num->sin - sin($num)), '<', $e ); cmp_ok( abs($num->sqrt - sqrt($num)), '<', $e ); cmp_ok( abs($num->atan2($num) - atan2($num, $num)), '<', $e ); autobox-Core-1.33/t/curry.t010064400017500000012000000003471134511145200147120ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my $times = sub { $_[0] * $_[1] }; my $times_two = $times->curry(2); my $times_four = $times->curry(4); is $times_two->(5), 10; is $times_four->(5), 20; autobox-Core-1.33/t/nm.t010064400017500000012000000001711264134561400141640ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; ok 'bar'->nm(qr/o+/); ok ! 'bar'->nm(qr/bar/); autobox-Core-1.33/t/strip.t010064400017500000012000000001761135075462300147200ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; is " \t \n \t foo \t \n \t "->strip, 'foo'; autobox-Core-1.33/t/synopsis.t010064400017500000012000000012771264236303100154430ustar00scottusersuse strict; use warnings; use Test::More tests => 7; use autobox::Core; is "Hello, World\n"->uc, "HELLO, WORLD\n"; my @list = (1, 5, 9, 2, 0, 4, 2, 1); is_deeply [@list->sort->reverse], [9,5,4,2,2,1,1,0]; # works with references too! my $list = [1, 5, 9, 2, 0, 4, 2, 1]; is_deeply [$list->sort->reverse], [9,5,4,2,2,1,1,0]; my %hash = ( grass => 'green', apple => 'red', sky => 'blue', ); is [10, 20, 30, 40, 50]->pop, 50; is [10, 20, 30, 40, 50]->shift, 10; my $lala = "Lalalalala\n"; is "chomp: "->concat($lala->chomp, " ", $lala), "chomp: 1 Lalalalala"; my $hashref = { foo => 10, bar => 20, baz => 30, qux => 40 }; is $hashref->keys->sort->join(' '), "bar baz foo qux"; autobox-Core-1.33/t/index.t010064400017500000012000000002751134511145200146550ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my $string = "I like pie"; my $substr = "pie"; is $string->index($substr), 7; is $string->index($substr, 8), -1; autobox-Core-1.33/t/m.t010064400017500000012000000001661264134561400140120ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; ok 'foo'->m(qr/o+/); ok ! 'foo'->m(qr/x+/); autobox-Core-1.33/t/range.t010064400017500001750000000006061165343654500146640ustar00scottscott#!/usr/bin/env perl use strict; use warnings; use Test::More tests => 4; use autobox::Core; my @array = qw(foo bar baz gorch); ok @array->range(0,1); is_deeply [@array->range(0,1)], ['foo', 'bar']; my @slice = @array->range(0,2); is scalar @slice, 3, "Returns an array in list context"; my $slice = @array->range(0,2); is ref $slice, 'ARRAY', "Returns an arrayref in scalar context"; autobox-Core-1.33/t/chop.t010064400017500000012000000006661134511145200145030ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my $string = "This is a string"; my $char = $string->chop; is $string, "This is a strin", "Chop modifies the string"; is $char, "g", "... and returns the last character"; TODO: { todo_skip "Chop should work on lists too", 2; my @list = qw(foo bar baz); my $char = @list->chop; is $char, 'z'; is_deeply \@list, [ 'fo', 'ba', 'ba' ]; } autobox-Core-1.33/t/join.t010064400017500000012000000002571134511145200145050ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my @list = qw(h i t h e r e); is @list->join(''), 'hithere'; is @list->join(' '), 'h i t h e r e'; autobox-Core-1.33/t/elements.t010064400017500000012000000003311134511145200153530ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my @array = qw(foo bar baz); my @returned = @array->elements; is_deeply \@returned, \@array; my $count = @array->elements; is $count, 3; autobox-Core-1.33/t/sprintf.t010064400017500001750000000002031165343654500152460ustar00scottscottuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my $format = "%.2f"; is $format->sprintf(2/3), "0.67"; autobox-Core-1.33/t/grep.t010064400017500000012000000017131264134561400145120ustar00scottusers#!/usr/bin/env perl use Test::More 'no_plan'; use strict; use warnings; use autobox::Core; my @array = qw(1 2 3); my @odd = @array->grep(sub { $_ % 2 }); is_deeply \@odd, [qw(1 3)], "Expected coderef grep results"; my $arrayref = @array->grep( sub { 'foo' } ); is ref $arrayref, 'ARRAY', "Returns arrayref in scalar context"; @array = qw( foo bar baz ); my $d; ok ( eval { @array->grep( sub { 42 } || 1) }, "Should accept code refs" ); ok ( eval { @array->grep( qr/foo/ ) || 1 }, "Should accept Regexps" ); is_deeply( $d = @array->grep('foo'), [qw( foo )], "Works with SCALAR" ); is_deeply( $d = @array->grep('zar'), [], "Works with SCALAR" ); is_deeply( $d = @array->grep(qr/^ba/), [qw( bar baz )], "Works with Regexp" ); is_deeply( $d = @array->grep(sub { /^ba/ }), [qw( bar baz )], "... as with Code refs" ); # context my @d = @array->grep(qr/^ba/); is scalar @d, 2, "Returns an array in list context"; autobox-Core-1.33/t/length.t010064400017500000012000000002731134511145200150250ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my $string = "THIS IS A STRING"; is $string->length, 16; my @array = qw(foo bar baz); is @array->length, 3; autobox-Core-1.33/t/chomp.t010064400017500000012000000002071134511145200146470ustar00scottusersuse Test::More qw(no_plan); use autobox::Core; my $line = "This has a new line\n"; $line->chomp; is $line, "This has a new line"; autobox-Core-1.33/t/added.t010064400017500000012000000043761302533675300146270ustar00scottusersuse Test::More 'no_plan'; use autobox::Core; ##################################################################### # Load ##################################################################### ok(1); ##################################################################### # Scalar ##################################################################### ok(1->and(5)); ok(!1->and(0)); ok(1->dec == 0); ok(1->inc == 2); ok(5->mod(2) == 1); ok(1->neg == -1); ok(not 1->not); ok(1->or(5)); ok(2->pow(5) == 32); ok(1->rpt(5) eq '11111'); ok(1->xor(5) == 0); ok("1+5"->eval() == 6); ok("echo test"->backtick =~ "test"); ok("echo test"->qx =~ "test"); # qx as an alias to backtick per #16 my $a = 1->to(10); ok($a->[0] == 1 && $a->[@$a-1] == 10); $a = 10->to(1); ok($a->[0] == 10 && $a->[@$a-1] == 1); my @a = 1->to(10); is_deeply \@a, [ 1 .. 10 ]; $a = 1->upto(10); ok($a->[0] == 1 && $a->[@$a-1] == 10); @a = 1->upto(10); is_deeply \@a, [ 1 .. 10 ]; $a = 10->downto(1); ok($a->[0] == 10 && $a->[@$a-1] == 1); @a = 10->downto(1); is_deeply \@a, [ reverse 1 .. 10 ]; ##################################################################### # Hashes ##################################################################### my $h = {a => 1, b => 2, c => 3}; is($h->at('b'), 2); is($h->get('c'), 3); $h->put('d' => 4, e=>5, f=>6); is($h->get('e'), 5); $h->put('g', 7); is($h->get('g'), 7); $h->set('h' => 8); is($h->get('h'), 8); $h->set('i', 9); is($h->get('i'), 9); is_deeply [$h->get(qw(a b c))], [1, 2, 3]; is_deeply( [ sort $h->flatten ], [ sort %$h ], "flattening gets us all the contents", ); ##################################################################### # Array ##################################################################### $a = 1->to(10); ok($a->sum == 55); ok($a->[0] == 1); ok($a->mean == 55/10); ok($a->var == 33/4); ok($a->svar == 55/6); ok($a->max == 10); ok($a->min == 1); ok($a->exists(5)); ok(not $a->exists(11)); $a = $a->map(sub {int($_/2)}); ok($a->exists(3)); $a->vdelete(3); ok(not $a->exists(3)); ok($a->at(0) == 0); ok($a->count(4) == 2); $a = $a->uniq; ok($a->count(1) == 1 && $a->count(4) == 1); ok($a->first == 0); ok($a->first(sub { m/4/ }) == 4); ok($a->first(qr/4/) == 4); $a = 1->to(10); $a->unshift(100); ok($a->sum == 155); autobox-Core-1.33/t/lc.t010064400017500000012000000002211134511145200141330ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my $string = "THIS IS A STRING"; is $string->lc, "this is a string"; autobox-Core-1.33/t/unpack.t010064400017500000012000000002611134511221600150210ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; SKIP: { skip "Only for 5.10", 1, if $] < 5.010; is 'W'->unpack("foo"), unpack('W', "foo"); }; autobox-Core-1.33/t/lcfirst.t010064400017500000012000000002271134511145200152110ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my $string = "THIS IS A STRING"; is $string->lcfirst, 'tHIS IS A STRING'; autobox-Core-1.33/t/foreach.t010064400017500000012000000003141134511145200151470ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my @array = qw(1 2 3); my @added; @array->foreach( sub { push @added, $_[0] + 1 } ); is_deeply [ sort @added ], [ qw(2 3 4) ]; autobox-Core-1.33/t/system.t010064400017500000012000000001461135075462300151000ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; is $^X->system(qw(-e1)), 0; autobox-Core-1.33/t/number.t010064400017500001750000000025421165343654500150610ustar00scottscott#!perl use Test::More tests => 49; use autobox::Core; #is( 12.34->ceil, 13); #is( 12.34->round_up, 13); #is( 12.34->floor, 12); #is( 12.34->round_down, 12); is( 12.34->int, 12); #is( 2.5->round, 3 ); #is( 2->round, 2 ); #is( 0->round, 0 ); #is( 2.51->round, 3 ); #is( -3.51->round, -4 ); ok( 12->is_number ); ok(!'FF'->is_number ); ok( 12->is_positive ); ok( "+12"->is_positive ); ok( 12.34->is_positive ); ok( !"foo"->is_positive ); ok( !"-12.2"->is_positive ); ok( !12->is_negative ); ok( "-12"->is_negative ); ok( (-12.34)->is_negative ); ok( !"foo"->is_negative ); ok( "-12.2"->is_negative ); ok !0->is_negative, "zero is not negative"; ok !0->is_positive, "zero is not positive"; ok( 12->is_integer ); ok( -12->is_integer ); ok( "+12"->is_integer ); ok(!12.34->is_integer ); ok( 12->is_int ); ok(!12.34->is_int ); ok( 12.34->is_decimal ); ok( ".34"->is_decimal ); ok( !12->is_decimal ); ok(!'abc'->is_decimal ); is( '123'->reverse, '321' ); TODO: { local $TODO = q{ hex is weird }; is( 255->hex, 'FF'); is( 'FF'->dec, 255); is( 0xFF->dec, 255); }; TODO: { todo_skip "Make number methods work on non-scalar refs", 20; for my $ref ([ 'foo' ], { bar => 1 }, \'baz', sub { 'gorch' }) { for my $method (qw(is_decimal is_integer is_int is_negative is_positive)) { ok(!$ref->$method); } } } autobox-Core-1.33/t/undef.t010064400017500000012000000002651135075462300146570ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my $foo = 'foo'; is $foo->undef, undef; is_deeply [1,2,3]->undef, []; is_deeply {foo => 123}->undef, +{}; autobox-Core-1.33/t/push.t010064400017500000012000000006331134511145200145230ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my @array = qw(foo bar); my @returned = @array->push('baz'); is_deeply \@array, [qw(foo bar baz)]; is_deeply \@returned, [qw(foo bar baz)]; my $arrayref = @array->push('baz'); is ref $arrayref, 'ARRAY', "Returns arrayref in scalar context"; my $array = [qw(foo bar)]; $array->push('baz'); is_deeply $array, [qw(foo bar baz)]; autobox-Core-1.33/t/print.t010064400017500000012000000010331134511244100146720ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my $message = "This is an important message"; my @array = qw(this is an important message); SKIP: { my $has_test_output = eval { require Test::Output }; skip "Don't have Test::Output", 2, if not $has_test_output; Test::Output::stdout_is( sub { $message->print }, $message ); Test::Output::stdout_is( sub { @array->print }, "@array" ); } # We need at least one test so that Test::Harness doesn't complain in # case we had to skip above ok 1; autobox-Core-1.33/t/for.t010064400017500000012000000003411134511145200143260ustar00scottusersuse Test::More qw(no_plan); use strict; use warnings; use autobox::Core; my @array = qw(1 2 3); my @added; @array->for( sub { my ($i, $v, $arr) = @_; push @added, $i + $v + @$arr } ); is_deeply [ @added ], [ qw(4 6 8) ]; autobox-Core-1.33/Changes010064400017500000012000000134361302533700200144120ustar00scottusersRevision history for autobox::Core 1.32 Docs - Corrected spelling mistake (thanks again Gregor Herrmann) 1.31 Docs - Corrected spelling mistake (thanks Gregor Herrmann) - Document that strings work as regexen (thanks jarich) New Features - Call backtick() qx() instead (but keep backtick around) (thanks jarich) Incompatible Changes - s() now returns the modified string or success/fail depending on context Fix - m() and nm() were failing to signal failure (thanks grtodd!) 1.30 New Features - first() arguments are now consistent with grep(), so now you can supply single non-ref scalar to it (xenu) Incompatible Changes - Removed smartmatch from first() and grep(). Now these methods have consistent behaviour under all perl versions and their code is much cleaner (xenu) Docs - Fixed typo reported by myfwhite on annocpan (xenu) 1.29 Fix - Suppress smartmatch deprecation warnings in perls >= 5.18 (xenu) 1.28 Misc - Make crypt() test optional for platforms without it (thanks Hugmeir) 1.27 Misc - new version just to creage a new .tar.gz. a './' owned by root apparently got added to the tar at some point after 'make dist'. 1.26 Fix - remove 'use feature' from t/synopsis.t. this lets older perls perl. 1.25 Wed Jun 12 14:45:54 CDT 2013 Fix - remove 'use feature' from t/synopsis.t. that was cut and paste from the docs but wasn't actually necessary there. 1.24 Sun Jul 15 11:05:11 PDT 2012 Misc - MANIFEST no longer includes previous distribution tar balls (Jacinta Richardson) 1.23 Thu Jul 12 18:05:46 PDT 2012 Docs - Minor corrections (Jacinta Richardson) 1.22 Thu Jul 12 17:16:06 PDT 2012 New Features - %hash->each is now guaranteed to iterate through the complete hash, unlike each(%hash). [github 7] - defined() Distribution Changes - Added Test::More 0.88 as a pre-req (Jacinta Richardson) - Added license for new versions of EMM Docs - Expanded module synopsis (Jacinta Richardson) - Wrote documentation for all (or most) functions - Tidied book extract (Jacinta Richardson) Incompatible changes (Jacinta Richardson) - Removed functions - rand - times - add - band - bor - bxor - div - eq - flip - ge - gt - le - lshift - mult - mcmp - ne - meq - mge - mgt - mle - mlt - mne - rshift - sub - autobox::Core::CODE::map Bug Fixes - xor uses xor instead of ^ (Jacinta Richardson) 1.21 Mon Sep 26 16:15:19 PDT 2011 New Features - $string->reverse will now always reverse the string regardless of context. (Technically an incompatible change, but the list behavior of $string->reverse was clearly useless). Distribution Changes - fix MANIFEST (thanks Steffen Müller). - move POD History section into standard Changes file (chocolateboy). - look, a change log! Misc - removed unnecessary prototypes on methods (schwern) - updated dependency on autobox 1.2 Fri Mar 19 12:11:00 2010 - fixes version 1.1 losing the MANIFEST and being essentially a null upload. Bah! - merges in brunov's flip, center, last_index, slice, range, documentation, and various bug fixes. 1.1 Thu Mar 18 13:33:00 2010 - actually adds the tests to the MANIFEST so they get bundled. - Thanks to http://github.com/daxim daxim/Lars DIECKOW for clearing out the RT queue (which I didn't know existed), merging in the fixes and features that still applied, which were several. 1.0 Sun Mar 7 22:35:00 2010 - is identical to 0.9. PAUSE tells me 0.9 already exists so bumping the number. *^%$! 0.10 Mon Jan 25 17:18:00 2010 - no change recorded. 0.9 Mon Jan 25 17:07:00 2010 - is identical to 0.8. PAUSE tells me 0.8 already exists so bumping the number. 0.8 Mon Jan 25 14:28:00 2010 - fixes unshift and pop to again return the value removed (oops, thanks brunov) and adds many, many more tests (wow, thanks brunov!). 0.7 Thu Mar 4 23:07:00 2010 - uses autobox itself so you don't have to, as requested, and ... oh hell. I started editing this to fix Schwern's reported v-string warning, but I'm not seeing it. - Use ~~ on @array->grep if we're using 5.10 or newer. - Add an explicit LICENSE section per request. - Took many tests and utility functions from perl5i. - Pays attention to wantarray and returns a list or the reference, as dictated by context. - flatten should rarely if ever be needed any more. 0.6 Mon May 26 05:19:00 2008 - propogates arguments to autobox and doesn't require you to use autobox. I still can't test it and am applying patches blindly. Maybe I'll drop the Hash::Util dep in the next version since it and Scalar::Util are constantly wedging on my system. The documentation needs to be updated and mention of Perl6::Contexts mostly removed. - JJ contributed a strip method for scalars - thanks JJ! 0.5 Tue May 13 23:59:00 2008 - has an $arrayref->unshift bug fix and and a new flatten method for hashes. - this version is untested because my Hash::Util stopped working, dammit. 0.4 Sat Jan 5 17:00:00 2008 - got numeric operations. 0.3 Wed Jan 5 21:12:00 2005 - fixes a problem where unpack wasn't sure it had enough arguments according to a test introduced in Perl 5.8.6 or perhaps 5.8.5. This problem was reported by Ron Reidy - thanks Ron! - added the references to Perl 6 Now and the excerpt. 0.2 Sat May 29 21:42:00 2004 - rounded out the API and introduced the beginnings of functional-ish methods. 0.1 Tue Mar 30 09:51:00 2004 - woefully incomplete initial version. autobox-Core-1.33/README010064400017500000012000000777361302533700200140140ustar00scottusersNAME 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 . 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 IO::Any Perl 6: . 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! Ricardo SIGNES contributed patches. Thanks to Matt Spear, who contributed tests and definitions for numeric operations. Mitchell N Charity reported a bug and sent a fix. Thanks to chocolateboy for autobox and for the encouragement. Thanks to Bruno Vecchi for bug fixes and many, many new tests going into version 0.8. Thanks to daxim/Lars DIECKOW pushing in fixes and patches from the RT queue along with fixes to build and additional doc examples. Thanks to everyone else who sent fixes or suggestions -- apologies if I failed to include you here! autobox-Core-1.33/Makefile.PL010064400017500001750000000016631264135441100151030ustar00scottscottuse ExtUtils::MakeMaker; # See lib/ExtUtils/MakeMaker.pm for details of how to influence # the contents of the Makefile that is written. WriteMakefile( NAME => 'autobox::Core', VERSION_FROM => 'lib/autobox/Core.pm', # finds $VERSION PREREQ_PM => { autobox => 2.71, 'Test::More' => 0.88, Want => 0.26, }, ABSTRACT_FROM => 'lib/autobox/Core.pm', # retrieve abstract from module AUTHOR => 'Scott Walters scott@slowass.net', (eval($ExtUtils::MakeMaker::VERSION) >= 6.31 ? (LICENSE => 'perl') : ()), CONFIGURE_REQUIRES => { 'ExtUtils::MakeMaker' => '6.46', # for META_MERGE }, META_MERGE => { resources => { bugtracker => 'http://github.com/scrottie/autobox-Core/issues', repository => 'http://github.com/scrottie/autobox-Core', } }, ); autobox-Core-1.33/MANIFEST.SKIP010064400017500000012000000020771215117335600150250ustar00scottusers #!start included /Users/schwern/perl5/perlbrew/perls/perl-5.14.1/lib/5.14.1/ExtUtils/MANIFEST.SKIP # Avoid version control files. \bRCS\b \bCVS\b \bSCCS\b ,v$ \B\.svn\b \B\.git\b \B\.gitignore\b \b_darcs\b \B\.cvsignore$ # Avoid VMS specific MakeMaker generated files \bDescrip.MMS$ \bDESCRIP.MMS$ \bdescrip.mms$ # Avoid Makemaker generated and utility files. \bMANIFEST\.bak \bMakefile$ \bblib/ \bMakeMaker-\d \bpm_to_blib\.ts$ \bpm_to_blib$ \bblibdirs\.ts$ # 6.18 through 6.25 generated this # Avoid Module::Build generated and utility files. \bBuild$ \b_build/ \bBuild.bat$ \bBuild.COM$ \bBUILD.COM$ \bbuild.com$ # Avoid temp and backup files. ~$ \.old$ \#$ \b\.# \.bak$ \.tmp$ \.# \.rej$ # Avoid OS-specific files/dirs # Mac OSX metadata \B\.DS_Store # Mac OSX SMB mount metadata files \B\._ # Avoid Devel::Cover and Devel::CoverX::Covered files. \bcover_db\b \bcovered\b # Avoid MYMETA files ^MYMETA\. #!end included /Users/schwern/perl5/perlbrew/perls/perl-5.14.1/lib/5.14.1/ExtUtils/MANIFEST.SKIP # avoid including tar balls from previous releases ^autobox-Core- autobox-Core-1.33/MANIFEST010064400017500000012000000016011302533716600142520ustar00scottusersChanges lib/autobox/Core.pm Makefile.PL MANIFEST This list of files MANIFEST.SKIP README t/added.t t/array-slice.t t/bless.t t/center.t t/chomp.t t/chop.t t/chr.t t/concat.t t/crypt.t t/curry.t t/each.t t/elements.t t/elems.t t/first_index.t t/flatten.t t/flip.t t/for.t t/foreach.t t/grep.t t/head.t t/index.t t/join.t t/keys.t t/last_index.t t/lc.t t/lcfirst.t t/length.t t/m.t t/map.t t/nm.t t/number.t t/numeric.t t/ord.t t/pack.t t/pop.t t/print.t t/push.t t/quotemeta.t t/range.t t/ref.t t/reverse.t t/rindex.t t/s.t t/say.t t/scalar.t t/shift.t t/size.t t/slice.t t/sort.t t/split.t t/sprintf.t t/strip.t t/substr.t t/synopsis.t t/system.t t/tail.t t/uc.t t/ucfirst.t t/undef.t t/unpack.t t/unshift.t t/values.t t/vec.t META.yml Module YAML meta-data (added by MakeMaker) META.json Module JSON meta-data (added by MakeMaker) autobox-Core-1.33/lib004075500017500000012000000000001302533716500136145ustar00scottusersautobox-Core-1.33/lib/autobox004075500017500000012000000000001302533716500152755ustar00scottusersautobox-Core-1.33/lib/autobox/Core.pm010064400017500000012000001370551302533705400166070ustar00scottuserspackage autobox::Core; use 5.008; use strict; use warnings; our $VERSION = '1.33'; use base 'autobox'; use B; use Want (); # 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 - Provide core functions to autoboxed scalars, arrays and hashes. =head1 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; =head1 DESCRIPTION The L module promotes Perl's primitive types (literals (strings and numbers), scalars, arrays and hashes) into first-class objects. However, L does not provide any methods for these new classes. L provides a set of methods for these new classes. It includes almost everything in L, some things from L and L, and some Perl 5 versions of methods taken from Perl 6. With F 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)); F makes it easier to avoid parentheses pile ups and messy dereferencing syntaxes. F is mostly glue. It presents existing functions with a new interface, while adding few extra. Most of the methods read like C<< sub hex { CORE::hex($_[0]) } >>. In addition to built-ins from L that operate on hashes, arrays, scalars, and code references, some Perl 6-ish things have been included, and some keywords like C are represented too. =head2 What's Implemented? =over 4 =item * Many of the functions listed in L under the headings: =over 4 =item * "Functions for real @ARRAYs", =item * "Functions for real %HASHes", =item * "Functions for list data", =item * "Functions for SCALARs or strings" =back plus a few taken from other sections and documented below. =item * Some methods from L and L. =item * Some things expected in Perl 6, such as C (C), C, and C. =item * C explicitly flattens an array. =back =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 and L, usually take it in the form of a compiled regex (C). Any modifiers can be attached to the C 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: L, L,L L, L, L L, L, L, L, L (always in scalar context), L, L, L, L L, L, L, L, L, L, L, L. In addition, so are each of the following: =head4 concat $string1->concat($string2); Concatenates C<$string2> to C<$string1>. This corresponds to the C<.> operator used to join two strings. Returns the joined 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 which allows for the removal of specific characters from the beginning and end of a string. =head4 trim Removes whitespace from the beginning and end of a string. C can also remove specific characters from the beginning and the end of string. ' hello'->trim; # 'hello' '*+* hello *+*'->trim("*+"); # ' hello ' ' *+* hello *+*'->trim("*+"); # ' *+* hello' =head4 ltrim Just like L but it only trims the left side (start) of the string. ' hello'->ltrim; # 'hello' '*+* hello *+*'->ltrim("*+"); # ' hello *+*' =head4 rtrim Just like L but it only trims the right side (end) of the string. 'hello '->rtrim; # 'hello' '*+* hello *+*'->rtrim("*+"); # '*+* hello ' =head4 split my @split_string = $string->split(qr/.../); my @split_string = $string->split(' '); A wrapper around L. 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. =head4 title_case C 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, or the length of $string, whichever is greater. C<$character> defaults to " ". say "Hello"->center(10); # " Hello "; say "Hello"->center(10, '-'); # "---Hello--"; C 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 qx my $output = $string->qx; Runs $string as a command just enclosing it backticks, as in C<`$string`>. =head4 nm if( $foo->nm(qr/bar/) ) { say "$foo did not match 'bar'"; } "Negative match". Corresponds to C<< !~ >>. Otherwise works in the same way as C. =head4 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 C<< m// >>, but the regex must be passed in as a C. C returns an array reference so that list functions such as C and C may be called on the result. Use C 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"; =head4 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 C<< s/// >>. In boolean context, it returns true/false to indicate whether the substitution succeeded. C, C, C, 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). =head4 undef $string->undef; Assigns C to the C<$string>. =head4 defined my $is_defined = $string->defined; if( not $string->defined ) { # give $string a value... } C tests whether a value is defined (not C). =head4 repeat my $repeated_string = $string->repeat($n); Like the C operator, repeats a string C<$n> times. print 1->repeat(5); # 11111 print "\n"->repeat(10); # ten newlines =head3 I/O Methods These are methods having to do with input and ouptut, not filehandles. =head4 print $string->print; Prints a string or a list of strings. Returns true if successful. =head4 say Like L, but implicitly appends a newline to the end. $string->say; =head3 Boolean Methods Methods related to boolean operations. =head4 and C corresponds to C<&&>. Returns true if both operands are true. if( $a->and($b) ) { ... } =head4 not C corresponds to C. Returns true if the subject is false. if( $a->not ) { ... } =head4 or C corresponds to C<||>. Returns true if at least one of the operands is true. if( $a->or($b) ) { ... } =head4 xor C corresponds to C. Returns true if only one of the operands is true. if( $a->xor($b) ) { ... } =head3 Number Related Methods Methods related to numbers. The basic built in functions which operate as normal : L, L, L, L, L, L, L, L, L, and L. The following operators were also included: =head4 dec $number->dec(); # $number is smaller by 1. C corresponds to C<++>. Decrements subject, will decrement character strings too: 'b' decrements to 'a'. =head4 inc C corresponds to C<++>. Increments subject, will increment character strings too. 'a' increments to 'b'. =head4 mod C corresponds to C<%>. $number->mod(5); =head4 pow C returns $number raised to the power of the $exponent. my $result = $number->pow($expontent); print 2->pow(8); # 256 =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, L, L, L. C, C, and C 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; # "4\n"; These built-in functions are defined as methods: L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, and L, L. As well as: =head4 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" =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 { qr/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 standard 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, elems, length C, C and C all return the number of elements in an array. my @array = qw(foo bar baz); @array->size; # 3 =head4 elements, 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 and C. 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, 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 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, C, and C 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 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>. This differs from L in that it does not change the array. 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 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(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 C<$#array> giving the highest index of the array. my $index = @array->last_index; =head4 first_index Works just like L but it will return the index of the I 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 =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, L, L, L, L, L, L, L, L, =head4 at, get my @values = %hash->get(@keys); Returns the @values of @keys. =head4 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) =head4 set Synonym for L. =head4 each Like C 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, 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's hash tables). You can get a sorted C by combining C, C, and C: %hash->keys->sort->foreach(sub { print $_[0], ' is ', $hash{$_[0]}, "\n"; }); =head4 lock_keys %hash->lock_keys; Works as L. 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 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 =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 functions. L, L, 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!" =head2 What's Missing? =over 4 =item * File and socket operations are already implemented in an object-oriented fashion care of L, L, and L. =item * Functions listed in the L headings =over 4 =item * "System V interprocess communication functions", =item * "Fetching user and group info", =item * "Fetching network info", =item * "Keywords related to perl modules", =item * "Functions for processes and process groups", =item * "Keywords related to scoping", =item * "Time-related functions", =item * "Keywords related to the control flow of your perl program", =item * "Functions for filehandles, files, or directories", =item * "Input and output functions". =back =item * (Most) binary operators =back 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. =head2 Autoboxing I A I 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 C<< my $number = Int->new(5) >>. This is manual boxing. To I is to convert a simple type into an object type automatically, or only conceptually. This is done by the language. Iing 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, C, C, C, 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, C, C, C, 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 and C work. Perl provides C to encapsulate an C, C to encapsulate a C, C to encapsulate a C, 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. Iing makes primitive objects and they're boxed versions equivalent. An C may be used as an C 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 C function exists. This first example would fail to operate if this global function were removed and only a method in the C 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 is a method on a filehandle we opened but I. 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 4 =item * Makes conceptual sense to programmers used to object interfaces as I 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. =item * Code may often be written with fewer temporary variables. =item * Autoboxing provides the benefits of boxed types without the memory bloat of actually using objects to represent primitives. Autoboxing "fakes it". =item * Strings, numbers, arrays, hashes, and so on, each have their own API. Documentation for an C method for arrays doesn't have to explain how hashes are handled and vice versa. =item * 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. =back Perl is an idiomatic language and this is an important idiom. =head3 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, C<< die $! unless read $file, 60 >> looks like the primary purpose of the statement is to C. 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: C<< 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. C<< $noun->verb() >> focuses the readers attention on the thing being acted on rather than the action being performed. Compare to C<< $verb($noun) >>. =head3 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. C recognizes object context as provided by C<< -> >> and coerces C<%hash> and C<@array> into references, suitable for use with C. (Note that C also does this automatically as of version 2.40.) C associates primitive types, such as references of various sorts, with classes. C throws into those classes methods wrapping Perl's built-in functions. In the interest of full disclosure, C and C are my creations. =head3 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 C don't span nearly as many characters. The complex expression serving as the value being Ced in the non-autoboxed version becomes, in the autoboxed version, a value to call the C method on. This C 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 I =head1 BUGS Yes. Report them to the author, scott@slowass.net, or post them to GitHub's bug tracker at L. The API is not yet stable -- Perl 6-ish things and local extensions are still being renamed. =head1 HISTORY See the Changes file. =head1 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. =head1 SEE ALSO =over 1 =item L =item L =item L =item L =item L =item Perl 6: L<< http://dev.perl.org/perl6/apocalypse/ >>. =back =head1 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 L contributors for tests, code, and feedback. JJ contributed a C method for scalars - thanks JJ! Ricardo SIGNES contributed patches. Thanks to Matt Spear, who contributed tests and definitions for numeric operations. Mitchell N Charity reported a bug and sent a fix. Thanks to chocolateboy for L and for the encouragement. Thanks to Bruno Vecchi for bug fixes and many, many new tests going into version 0.8. Thanks to L daxim/Lars DIECKOW pushing in fixes and patches from the RT queue along with fixes to build and additional doc examples. Thanks to Johan Lindstrom for bug reports. Thanks to everyone else who sent fixes or suggestions -- apologies if I failed to include you here! =cut # # SCALAR # package autobox::Core::SCALAR; # Functions for SCALARs or strings # "chomp", "chop", "chr", "crypt", "hex", "index", "lc", # "lcfirst", "length", "oct", "ord", "pack", # "q/STRING/", "qq/STRING/", "reverse", "rindex", # "sprintf", "substr", "tr///", "uc", "ucfirst", "y///" # current doesn't handle scalar references - get can't call method chomp on unblessed reference etc when i try to support it sub chomp { CORE::chomp($_[0]); } sub chop { CORE::chop($_[0]); } sub chr { CORE::chr($_[0]); } sub crypt { CORE::crypt($_[0], $_[1]); } sub index { $_[2] ? CORE::index($_[0], $_[1], $_[2]) : CORE::index($_[0], $_[1]); } sub lc { CORE::lc($_[0]); } sub lcfirst { CORE::lcfirst($_[0]); } sub length { CORE::length($_[0]); } sub ord { CORE::ord($_[0]); } sub pack { CORE::pack(shift, @_); } sub reverse { # Always reverse scalars as strings, never as a single element list. return scalar CORE::reverse($_[0]); } sub rindex { return CORE::rindex($_[0], $_[1]) if @_ == 2; return CORE::rindex($_[0], $_[1], @_[2.. $#_]); } sub sprintf { CORE::sprintf($_[0], $_[1], @_[2.. $#_]); } sub substr { return CORE::substr($_[0], $_[1]) if @_ == 2; return CORE::substr($_[0], $_[1], @_[2 .. $#_]); } sub uc { CORE::uc($_[0]); } sub ucfirst { CORE::ucfirst($_[0]); } sub unpack { CORE::unpack($_[0], @_[1..$#_]); } sub quotemeta { CORE::quotemeta($_[0]); } sub vec { CORE::vec($_[0], $_[1], $_[2]); } sub undef { $_[0] = undef } sub defined { CORE::defined($_[0]) } sub m { my @ms = $_[0] =~ m{$_[1]} ; return @ms ? \@ms : undef } sub nm { my @ms = $_[0] =~ m{$_[1]} ; return @ms ? undef : \@ms } sub split { wantarray ? split $_[1], $_[0] : [ split $_[1], $_[0] ] } sub s { my $success = ( $_[0] =~ s{$_[1]}{$_[2]} ) ? 1 : 0; if (Want::want('LIST')) { Want::rreturn ($_[0]); } elsif (Want::want('BOOL')) { # this needs to happen before the SCALAR context test Want::rreturn $success; } elsif (Want::want(qw'SCALAR')) { Want::rreturn $_[0]; } return; # "You have to put this at the end to keep the compiler happy" from Want docs } sub eval { CORE::eval "$_[0]"; } sub system { CORE::system @_; } sub backtick { `$_[0]`; } sub qx { `$_[0]`; } # per #16, "backtick should probably be called qx" # Numeric functions sub abs { CORE::abs($_[0]) } sub atan2 { CORE::atan2($_[0], $_[1]) } sub cos { CORE::cos($_[0]) } sub exp { CORE::exp($_[0]) } sub int { CORE::int($_[0]) } sub log { CORE::log($_[0]) } sub oct { CORE::oct($_[0]) } sub hex { CORE::hex($_[0]); } sub sin { CORE::sin($_[0]) } sub sqrt { CORE::sqrt($_[0]) } # functions for array creation sub to { my $res = $_[0] < $_[1] ? [$_[0]..$_[1]] : [CORE::reverse $_[1]..$_[0]]; return wantarray ? @$res : $res } sub upto { return wantarray ? ($_[0]..$_[1]) : [ $_[0]..$_[1] ] } sub downto { my $res = [ CORE::reverse $_[1]..$_[0] ]; return wantarray ? @$res : $res } # Lars D didn't explain the intention of this code either in a comment or in docs and I don't see the point #sub times { # if ($_[1]) { # for (0..$_[0]-1) { $_[1]->($_); }; $_[0]; # } else { # 0..$_[0]-1 # } #} # doesn't minipulate scalars but works on scalars sub print { CORE::print @_; } sub say { CORE::print @_, "\n"} # operators that work on scalars: sub concat { CORE::join '', @_; } sub strip { my $s = CORE::shift; $s =~ s/^\s+//; $s =~ s/\s+$//; return $s; } # operator schizzle sub and { $_[0] && $_[1]; } sub dec { my $t = CORE::shift @_; --$t; } sub inc { my $t = CORE::shift @_; ++$t; } sub mod { $_[0] % $_[1]; } sub neg { -$_[0]; } sub not { !$_[0]; } sub or { $_[0] || $_[1]; } sub pow { $_[0] ** $_[1]; } sub xor { $_[0] xor $_[1]; } # rpt should go sub repeat { $_[0] x $_[1]; } sub rpt { $_[0] x $_[1]; } # sub bless (\%$) { CORE::bless $_[0], $_[1] } # HASH, ARRAY, CODE already have a bless() and blessing a non-reference works (autobox finds the reference in the pad or stash!). "can't bless a non-referenc value" for non-reference lexical and package scalars. this would work for (\$foo)->bless but then, unlike arrays, we couldn't find the reference to the variable again later so there's not much point I can see. # from perl5i: sub title_case { my ($string) = @_; $string =~ s/\b(\w)/\U$1/g; return $string; } sub center { my ($string, $size, $char) = @_; Carp::carp("Use of uninitialized value for size in center()") if !defined $size; $size = defined($size) ? $size : 0; $char = defined($char) ? $char : ' '; if (CORE::length $char > 1) { my $bad = $char; $char = CORE::substr $char, 0, 1; Carp::carp("'$bad' is longer than one character, using '$char' instead"); } my $len = CORE::length $string; return $string if $size <= $len; my $padlen = $size - $len; # pad right with half the remaining characters my $rpad = CORE::int( $padlen / 2 ); # bias the left padding to one more space, if $size - $len is odd my $lpad = $padlen - $rpad; return $char x $lpad . $string . $char x $rpad; } sub ltrim { my ($string,$trim_charset) = @_; $trim_charset = '\s' unless defined $trim_charset; my $re = qr/^[$trim_charset]*/; $string =~ s/$re//; return $string; } sub rtrim { my ($string,$trim_charset) = @_; $trim_charset = '\s' unless defined $trim_charset; my $re = qr/[$trim_charset]*$/; $string =~ s/$re//; return $string; } sub trim { my $charset = $_[1]; return rtrim(ltrim($_[0], $charset), $charset); } # POSIX is huge #require POSIX; #*ceil = \&POSIX::ceil; #*floor = \&POSIX::floor; #*round_up = \&ceil; #*round_down = \&floor; #sub round { # abs($_[0] - int($_[0])) < 0.5 ? round_down($_[0]) # : round_up($_[0]) #} require Scalar::Util; *is_number = \&Scalar::Util::looks_like_number; sub is_positive { Scalar::Util::looks_like_number($_[0]) && $_[0] > 0 } sub is_negative { Scalar::Util::looks_like_number($_[0]) && $_[0] < 0 } sub is_integer { Scalar::Util::looks_like_number($_[0]) && ((CORE::int($_[0]) - $_[0]) == 0) } *is_int = \&is_integer; sub is_decimal { Scalar::Util::looks_like_number($_[0]) && ((CORE::int($_[0]) - $_[0]) != 0) } ########################################################## # # HASH # package autobox::Core::HASH; use Carp 'croak'; # Functions for real %HASHes sub delete { my $hash = CORE::shift; my @res = (); foreach(@_) { push @res, CORE::delete $hash->{$_}; } return wantarray ? @res : \@res } sub exists { my $hash = CORE::shift; return CORE::exists $hash->{$_[0]}; } sub keys { return wantarray ? CORE::keys %{$_[0]} : [ CORE::keys %{$_[0]} ]; } sub values { return wantarray ? CORE::values %{$_[0]} : [ CORE::values %{$_[0]} ] } # local extensions sub get { @{$_[0]}{@_[1..$#_]}; } *at = *get; sub put { my $h = CORE::shift @_; my %h = @_; while(my ($k, $v) = CORE::each %h) { $h->{$k} = $v; }; return $h; } sub set { my $h = CORE::shift @_; my %h = @_; while(my ($k, $v) = CORE::each %h) { $h->{$k} = $v; }; return $h; } sub flatten { %{$_[0]} } sub each { my $hash = CORE::shift; my $cb = CORE::shift; # Reset the each iterator. (This is efficient in void context) CORE::keys %$hash; while((my $k, my $v) = CORE::each(%$hash)) { # local $_ = $v; # XXX may I break stuff? $cb->($k, $v); } return; } # Keywords related to classes and object-orientedness sub bless { CORE::bless $_[0], $_[1] } sub tie { CORE::tie $_[0], @_[1 .. $#_] } sub tied { CORE::tied $_[0] } sub ref { CORE::ref $_[0] } sub undef { $_[0] = {} } sub slice { my ($h, @keys) = @_; wantarray ? @{$h}{@keys} : [ @{$h}{@keys} ]; } # okey, ::Util stuff should be core use Hash::Util; sub lock_keys { Hash::Util::lock_keys(%{$_[0]}); $_[0]; } # from perl5i sub flip { croak "Can't flip hash with references as values" if grep { CORE::ref } CORE::values %{$_[0]}; return wantarray ? reverse %{$_[0]} : { reverse %{$_[0]} }; } # # ARRAY # ############################################################################################## package autobox::Core::ARRAY; use Carp 'croak'; # Functions for list data # at one moment, perl5i had this in it: #sub grep { # my ( $array, $filter ) = @_; # my @result = CORE::grep { $_ ~~ $filter } @$array; # return wantarray ? @result : \@result; #} sub grep { my $arr = CORE::shift; my $filter = CORE::shift; my @result; if( CORE::ref $filter eq 'Regexp' ) { @result = CORE::grep { m/$filter/ } @$arr; } elsif( ! CORE::ref $filter ) { @result = CORE::grep { $filter eq $_ } @$arr; # find all of the exact matches } else { @result = CORE::grep { $filter->($_) } @$arr; } return wantarray ? @result : \@result; } # last version: sub map (\@&) { my $arr = CORE::shift; my $sub = shift; [ CORE::map { $sub->($_) } @$arr ]; } sub map { my( $array, $code ) = @_; my @result = CORE::map { $code->($_) } @$array; return wantarray ? @result : \@result; } sub join { my $arr = CORE::shift; my $sep = CORE::shift; CORE::join $sep, @$arr; } sub reverse { my @res = CORE::reverse @{$_[0]}; wantarray ? @res : \@res; } sub sort { my $arr = CORE::shift; my $sub = CORE::shift() || sub { $a cmp $b }; my @res = CORE::sort { $sub->($a, $b) } @$arr; return wantarray ? @res : \@res; } # functionalish stuff sub sum { my $arr = CORE::shift; my $res = 0; $res += $_ foreach(@$arr); $res; } sub mean { my $arr = CORE::shift; my $res = 0; $res += $_ foreach(@$arr); $res/@$arr; } sub var { my $arr = CORE::shift; my $mean = 0; $mean += $_ foreach(@$arr); $mean /= @$arr; my $res = 0; $res += ($_-$mean)**2 foreach (@$arr); $res/@$arr; } sub svar { my $arr = CORE::shift; my $mean = 0; $mean += $_ foreach(@$arr); $mean /= @$arr; my $res = 0; $res += ($_-$mean)**2 foreach (@$arr); $res/(@$arr-1); } sub max { my $arr = CORE::shift; my $max = $arr->[0]; foreach (@$arr) { $max = $_ if $_ > $max } return $max; } sub min { my $arr = CORE::shift; my $min = $arr->[0]; foreach (@$arr) { $min = $_ if $_ < $min } return $min; } # Functions for real @ARRAYs sub pop { CORE::pop @{$_[0]}; } sub push { my $arr = CORE::shift; CORE::push @$arr, @_; return wantarray ? return @$arr : $arr; } sub unshift { my $a = CORE::shift; CORE::unshift(@$a, @_); return wantarray ? @$a : $a; } sub delete { my $arr = CORE::shift; CORE::delete $arr->[$_[0]]; return wantarray ? @$arr : $arr } sub vdelete { my $arr = CORE::shift; @$arr = CORE::grep {$_ ne $_[0]} @$arr; return wantarray ? @$arr : $arr } sub shift { my $arr = CORE::shift; return CORE::shift @$arr; } sub undef { $_[0] = [] } # doesn't modify array sub exists { my $arr = CORE::shift; return CORE::scalar( CORE::grep {$_ eq $_[0]} @$arr ) > 0; } sub at { my $arr = CORE::shift; return $arr->[$_[0]]; } sub count { my $arr = CORE::shift; return CORE::scalar(CORE::grep {$_ eq $_[0]} @$arr); } sub uniq { my $arr = CORE::shift; # shamelessly stolen from List::MoreUtils # fix for code stolen from List::MoreUtils shamelessly stolen from List::MoreUtils my %seen = (); my $k; my $seen_undef; my @res = CORE::grep { CORE::defined $_ ? not $seen{ $k = $_ }++ : CORE::not $seen_undef++ } @$arr; return wantarray ? @res : \@res; } # tied and blessed sub bless { CORE::bless $_[0], $_[1] } sub tie { CORE::tie $_[0], @_[1 .. $#_] } sub tied { CORE::tied $_[0] } sub ref { CORE::ref $_[0] } # perl 6-ish extensions to Perl 5 core stuff # sub first(\@) { my $arr = CORE::shift; $arr->[0]; } # old, incompat version sub first { # from perl5i, modified # XXX needs test. take from perl5i? my ( $array, $filter ) = @_; if ( @_ == 1 ) { return $array->[0]; } elsif ( CORE::ref $filter eq "Regexp" ) { return List::Util::first( sub { $_ =~ m/$filter/ }, @$array ); } elsif ( ! CORE::ref $filter ) { return List::Util::first( sub { $_ eq $filter }, @$array ); } else { return List::Util::first( sub { $filter->() }, @$array ); } } sub size { my $arr = CORE::shift; CORE::scalar @$arr; } sub elems { my $arr = CORE::shift; CORE::scalar @$arr; } # Larry announced it would be elems, not size sub length { my $arr = CORE::shift; CORE::scalar @$arr; } # misc sub each { # same as foreach(), apo12 mentions this # XXX should we try to build a result list if we're in non-void context? my $arr = CORE::shift; my $sub = CORE::shift; foreach my $i (@$arr) { # local $_ = $i; # XXX may I break stuff? $sub->($i); } } sub foreach { my $arr = CORE::shift; my $sub = CORE::shift; foreach my $i (@$arr) { # local $_ = $i; # XXX may I break stuff? $sub->($i); } } sub for { my $arr = CORE::shift; my $sub = CORE::shift; for(my $i = 0; $i <= $#$arr; $i++) { # local $_ = $arr->[$i]; # XXX may I break stuff? $sub->($i, $arr->[$i], $arr); } } sub print { my $arr = CORE::shift; my @arr = @$arr; CORE::print "@arr"; } sub say { my $arr = CORE::shift; my @arr = @$arr; CORE::print "@arr\n"; } # local sub elements { ( @{$_[0]} ) } sub flatten { ( @{$_[0]} ) } sub head { return $_[0]->[0]; } sub slice { my $list = CORE::shift; # the rest of the arguments in @_ are the indices to take return wantarray ? @$list[@_] : [@{$list}[@_]]; } sub range { my ($array, $lower, $upper) = @_; my @slice = @{$array}[$lower .. $upper]; return wantarray ? @slice : \@slice; } sub tail { my $last = $#{$_[0]}; my $first = defined $_[1] ? $last - $_[1] + 1 : 1; Carp::croak("Not enough elements in array") if $first < 0; # Yeah... avert your eyes return wantarray ? @{$_[0]}[$first .. $last] : [@{$_[0]}[$first .. $last]]; } sub first_index { if (@_ == 1) { return 0; } else { my ($array, $arg) = @_; my $filter = CORE::ref($arg) eq 'Regexp' ? sub { $_[0] =~ $arg } : $arg; foreach my $i (0 .. $#$array) { return $i if $filter->($array->[$i]); } return } } sub last_index { if (@_ == 1) { return $#{$_[0]}; } else { my ($array, $arg) = @_; my $filter = CORE::ref($arg) eq 'Regexp' ? sub { $_[0] =~ $arg } : $arg; foreach my $i (CORE::reverse 0 .. $#$array ) { return $i if $filter->($array->[$i]); } return } } ############################################################################################## # # CODE # package autobox::Core::CODE; sub bless { CORE::bless $_[0], $_[1] } sub ref { CORE::ref $_[0] } # perl 6-isms sub curry { my $code = CORE::shift; my @args = @_; sub { CORE::unshift @_, @args; goto &$code; }; } 1; autobox-Core-1.33/META.yml010064400017500000012000000013631302533716600143770ustar00scottusers--- abstract: 'Provide core functions to autoboxed scalars, arrays and hashes.' author: - 'Scott Walters scott@slowass.net' build_requires: ExtUtils::MakeMaker: '0' configure_requires: ExtUtils::MakeMaker: '6.46' dynamic_config: 1 generated_by: 'ExtUtils::MakeMaker version 6.98, CPAN::Meta::Converter version 2.150005' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: autobox-Core no_index: directory: - t - inc requires: Test::More: '0.88' Want: '0.26' autobox: '2.71' resources: bugtracker: http://github.com/scrottie/autobox-Core/issues repository: http://github.com/scrottie/autobox-Core version: '1.33' x_serialization_backend: 'CPAN::Meta::YAML version 0.012' autobox-Core-1.33/META.json010064400017500000012000000023411302533716600145440ustar00scottusers{ "abstract" : "Provide core functions to autoboxed scalars, arrays and hashes.", "author" : [ "Scott Walters scott@slowass.net" ], "dynamic_config" : 1, "generated_by" : "ExtUtils::MakeMaker version 6.98, CPAN::Meta::Converter version 2.150005", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "autobox-Core", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "6.46" } }, "runtime" : { "requires" : { "Test::More" : "0.88", "Want" : "0.26", "autobox" : "2.71" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "http://github.com/scrottie/autobox-Core/issues" }, "repository" : { "url" : "http://github.com/scrottie/autobox-Core" } }, "version" : "1.33", "x_serialization_backend" : "JSON::PP version 2.27203" }