Skip to content
Release history of autobox-Core
Find file
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.


autobox::Core(3)      User Contributed Perl Documentation     autobox::Core(3)

       autobox::Core - Core functions exposed as methods in primitive types

         use autobox::Core;

         "Hello, World\n"->uc->print;

       The autobox module lets you call methods on primitive datatypes such as
       scalars and arrays.

       autobox::CORE defines methods for core operations such as "join",
       "print", most everything in perlfunc, some things from Scalar::Util and
       List::Util, and some Perl 5 versions of methods taken from Perl 6.

       These methods expose as methods the built-in functions for minipulating
       numbers, strings, arrays, hashes, and code references.

       It can be handy to use built-in functions as methods to avoid messy
       dereferencing syntaxes and parentheses pile ups.

       _�a_�u_�t_�o_�b_�o_�x_�:_�:_�C_�o_�r_�e is what you'd call a _�s_�t_�u_�b module. It is merely glue, pre-
       senting existing functions with a new interface. Most of the methods
       read like "sub hex ($) { hex($_[0]) }".  Besides built-ins that operate
       on hashes, arrays, scalars, and code references, some Perl 6-ish things
       were thrown in, and some keyword like "foreach" have been turned into

       W�Wh�ha�at�t'�'s�s I�Im�mp�pl�le�em�me�en�nt�te�ed�d?�?

       All of the functions listed in perldoc under the headings: "Functions
       for real @ARRAYs", "Functions for real %HASHes", "Functions for list
       data", and "Functions for SCALARs or strings", plus a few taken from
       other sections and documented below.  Methods from Scalar::Util and
       List::Util were thrown in.  Some things expected in Perl 6, such as
       "last" ("last_idx"), "elems", and "curry", have been thrown in.  "flat-
       ten" explicitly flattens an array.  Functions such as "add" have been
       defined for numeric operations.

       Here's a small sample:

         print [10, 20, 30, 40, 50]->pop, "\n";
         print [10, 20, 30, 40, 50]->shift, "\n";

         my $arrref = [10, 20, 30];

         my $lala;
         $lala = "Lalalalala\n"; print "chomp: ", $lala->chomp, ' ', $lala, "\n";
         $lala = "Lalalalala\n"; print "lcfirst: ", $lala->lcfirst, ' ', $lala, "\n";

         my $hashref = { foo => 10, bar => 20, baz => 30, qux => 40 };
         print "hash keys: ", join ' ', $hashref->keys(), "\n";

       Of the built-in stuff, only a few stragglers such as "srand" were

       _�S_�c_�a_�l_�a_�r _�S_�t_�r_�i_�n_�g _�R_�e_�l_�a_�t_�e_�d _�M_�e_�t_�h_�o_�d_�s

       "concat" is the "." operator.

       "strip" is not a built-in operator or function but is instead one of a
       number of user-defined convinience methods.  "strip" strips out white-
       space from the beginning and end of a string.  This is redundant and
       subtely different from "trim" XXX.

       "trim" strips out whitespace from the beginning and end of a string.

       "title_case", "center", "ltrim", "rtrim", and "trim" were taken from

       "split" is called on a non-reference scalar with the regular expression
       passed in. This is done for consistency with "m" and "s".

         print "10, 20, 30, 40"->split(qr{, ?})->elements, "\n";

       "chomp", "chop", "chr", "crypt", "index", "lc", "lcfirst", "length",
       "ord", "pack", "reverse", "rindex", "sprintf", "substr", "uc",
       "ucfirst", "unpack", "quotemeta", "vec", "undef", "m", "nm", "s",
       "split".  "eval", "system", and "backtick".

       "m" matches:  "$foo->m(/bar/)" corresponds to "$foo =~ m/bar/".  "nm"
       corresponds to "!~".  "s" corresponds to "=~ s///".

       "undef" assigns "undef" to the value.  It is not a test.  XXX for some
       reason, there's no "defined".


       "print" and "say".

       _�N_�u_�m_�b_�e_�r _�R_�e_�l_�a_�t_�e_�d _�M_�e_�t_�h_�o_�d_�s

       "abs", "atan2", "cos", "exp", "int", "log", "oct", "hex", "rand",
       "sin", and "sqrt" are named after the built-in functions of the same

       Operators were given names as follows:  "add", "and", "band", "bor",
       "bxor", "cmp", "dec", "div", "eq", "flip", "ge", "gt", "inc", "le",
       "lshift", "lt", "mod", "mult", "mcmp", "ne", "neg", "meq", "mge",
       "mgt", "mle", "mlt", "mne", "not", "or", "pow", "rpt", "rshift", "sub",

       "flip" is "~" which is the binary (rather than boolean) "not".

       "lshift" is "<<" and "rshift" is ">>".

       "mge" is ">=".  "<mle"> is "<=".  I'm not sure where the "m" came from.

       "sub" is subtract, I think, but it should not be named the same as the
       anonymous subroutine constructor XXX.

       *is_number = \&Scalar::Util::looks_like_number; sub is_positive
       { $_[0]->is_number && $_[0] > 0 } sub is_negative         {
       $_[0]->is_number && $_[0] < 0 } sub is_integer          {
       $_[0]->is_number && ((int($_[0]) - $_[0]) == 0) } *is_int = \&is_inte-
       ger; sub is_decimal          { $_[0]->is_number && ((int($_[0]) -
       $_[0]) != 0) }

       That's it.

       _�R_�e_�f_�e_�r_�e_�n_�c_�e _�R_�e_�l_�a_�t_�e_�d _�M_�e_�t_�h_�o_�d_�s

       Besides the "Functions for SCALARs" section of perlfunc, the following
       were implemented, where they make sense: "tie", "tied", "ref", "undef",
       "bless", and "vec".  "tie", "tied", and "undef" don't work on code ref-
       erences, and "bless" doesn't work on non-reference scalars (okay,
       that's no longer true).  "quotemeta" works on non-reference scalars,
       along with "split", "m", and "s" for regular expression operations.
       "ref" is the same as the "ref" keyword in that it tells you what kind
       of a reference something is if it's a reference; XXX there's currently
       no counterpart to the "\" operator, which takes something and gives you
       a reference to it.

       _�A_�r_�r_�a_�y _�M_�e_�t_�h_�o_�d_�s

         my $arr = [ 1 .. 10 ];

       Array references can tell you how many elements they contain and the
       index of their last element:

         my $arr = [ 1 .. 10 ];
         print '$arr contains ', $arr->size,
               ' elements, the last having an index of ', $arr->last_index, "\n";

       Array references have a "flatten" method to dump their elements.  This
       is the same as "@{$array_ref}".

         my $arr = [ 1 .. 10 ];
         print join " -- ", $arr->flatten, "\n";

       Array references can be iterated on using "for" and "foreach". Both
       take a code reference as the body of the for statement.  "foreach"
       passes the current element itself in each pass.  "for" passes the index
       of the current element in to that code block, and then the current ele-
       ment, and then a reference to the array itself.

         my $arr = [ 1 .. 10 ];
         $arr->foreach(sub { print $_[0], "\n" });
         $arr->for(sub { die unless $_[1] == $_[2]->[$_[0]] });

       "sum" is a toy poke at doing Language::Functional-like stuff:

         print $arrref->sum, "\n";

       XXX round this out

       Methods for array creation:  "to", "upto", and "downto".

         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]

       These wrap the ".." operator.

         $arr->first(sub { /5/ });

       _�H_�a_�s_�h _�M_�e_�t_�h_�o_�d_�s

       "each" is 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" });

       There is currently no way to have the elements sorted before they are
       handed to the code block. If someone requests a way of passing in a
       sort criteria, I'll implement it.

       "m" is "m//" and "s" is "s///". These work on scalars.  Pass a regular
       expression created with "qr//" and specify flags to the regular expres-
       sion as part of the regular expression using the "(?imsx-imsx)" syntax
       documented in perlre.  "m" returns an array reference so that things
       such as "map" and "grep" may be called on the result.

         my ($street_number, $street_name, $apartment_number) =
             "1234 Robin Drive #101"->m(qr{(\d+) (.*)(?: #(\d+))?})->elements;

         print "$street_number $street_name $apartment_number\n";

       _�C_�o_�d_�e _�M_�e_�t_�h_�o_�d_�s

       You may "curry" code references:

         $adding_up_numbers = sub {
             my $first_number = shift;
             my $second_number = shift;
             return $first_number + $second_number;

         my $adding_five_to_numbers = $adding_up_numbers->curry(5);

         $adding_five_to_numbers->(20)->print; "\n"->print;

       "times" executes a coderef a given number of times:

         5->times(sub { print "hi\n"});   # XXX likely to change but it's in the code so bloody doc it so I have incentive to rethink it

       XXX round this out

       W�Wh�ha�at�t'�'s�s M�Mi�is�ss�si�in�ng�g?�?

       Many operators.  I'm tired.  I'll do it in the morning.  Maybe.  Send
       me a patch.  Update:  Someone sent me a patch for numeric operations.

       File and socket operations are already implemented in an object-ori-
       ented fashion care of IO::Handle, IO::Socket::INET, and IO::Any.

       Functions listed in the perlfunc headings "System V interprocess commu-
       nication 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 func-
       tions", "Keywords related to the control flow of your perl program",
       "Functions for filehandles, files, or directories", and "Input and out-
       put functions".  These things are likely implemented in an object ori-
       ented 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.  "srand" because you probably shouldn't be
       using it.

       "each" on hashes. There is no good reason it is missing.  XXX.


       _�T_�h_�i_�s _�s_�e_�c_�t_�i_�o_�n _�q_�u_�o_�t_�e_�s _�f_�o_�u_�r _�p_�a_�g_�e_�s _�f_�r_�o_�m _�t_�h_�e _�m_�a_�n_�u_�s_�c_�r_�i_�p_�t _�o_�f _�P_�e_�r_�l _�6 _�N_�o_�w_�: _�T_�h_�e
       _�C_�o_�r_�e _�I_�d_�e_�a_�s _�I_�l_�l_�u_�s_�t_�r_�a_�t_�e_�d _�w_�i_�t_�h _�P_�e_�r_�l _�5 _�b_�y _�m_�y_�s_�e_�l_�f_�, _�S_�c_�o_�t_�t _�W_�a_�l_�t_�e_�r_�s_�. _�T_�h_�e _�t_�e_�x_�t
       _�a_�p_�p_�e_�a_�r_�s _�i_�n _�t_�h_�e _�b_�o_�o_�k _�s_�t_�a_�r_�t_�i_�n_�g _�a_�t _�p_�a_�g_�e _�2_�4_�8_�. _�T_�h_�i_�s _�c_�o_�p_�y _�l_�a_�c_�k_�s _�t_�h_�e _�b_�e_�n_�e_�f_�i_�t
       _�o_�f _�c_�o_�p_�y_�e_�d_�i_�t _�- _�t_�h_�e _�f_�i_�n_�i_�s_�h_�e_�d _�p_�r_�o_�d_�u_�c_�t _�i_�s _�o_�f _�h_�i_�g_�h_�e_�r _�q_�u_�a_�l_�i_�t_�y_�. _�S_�e_�e _�t_�h_�e _�s_�h_�a_�m_�e_�-
       _�l_�e_�s_�s _�p_�l_�u_�g _�i_�n _�t_�h_�e _�S_�E_�E _�A_�L_�S_�O _�s_�e_�c_�t_�i_�o_�n _�f_�o_�r _�i_�n_�f_�o_�r_�m_�a_�t_�i_�o_�n _�o_�n _�o_�r_�d_�e_�r_�i_�n_�g _�P_�e_�r_�l _�6

       A _�b_�o_�x is an object that contains a primitive variable.  Boxes are used
       to endow primitive types with the capabilities of objects.  This is
       essential in strongly typed languages but never strictly required in
       Perl.  Programmers might write something like "my $number =
       Int->new(5)".  This is manual boxing.  To _�a_�u_�t_�o_�b_�o_�x is to convert a sim-
       ple type into an object type automatically, or only conceptually.  This
       is done by the language.  It makes a language look to programmers as if
       everything is an object while the interpreter is free to implement data
       storage however it pleases.  Autoboxing is really making simple types
       such as numbers, strings, and arrays appear to be objects.

       "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 ancil-
       lary benefits such as making "is" and "has" work.  Perl provides "Int"
       to encapsulate an "int", "Num" to encapsulate a "num", "Bit" to encap-
       sulate 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.

       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:

         # Perl 6 - autoboxing associates classes with primitives types:

         print 4.sqrt, "\n";

       This is perfectly valid Perl 6.

       All of this applies to hashes and arrays, as well:

         # Perl 6 - autoboxing associates classes with primitive types:

         print [ 1 .. 20 ].elems, "\n";

       The language is free to implement data storage however it wishes but
       the programmer sees the variables as objects.

       Expressions using autoboxing read somewhat like Latin suffixes.  In the
       autoboxing mind-set, you might not say that something is "made more
       mnemonic", but has been "mnemonicified".

       Autoboxing may be mixed with normal function calls.  In the case where
       the methods are available as functions and the functions are available
       as methods, it is only a matter of personal taste how the expression
       should be written:

         # Calling methods on numbers and strings, these three lines are equivalent
         # Perl 6

         print sqrt 4;
         print 4.sqrt;

       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

       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 _�n_�e_�v_�e_�r _�b_�l_�e_�s_�s_�e_�d.
       This lets us say things like "$file->print(...)" rather than the often

       "print $file ...".  To many people, much of the time, it makes more
       conceptual sense as well.

       _�R_�e_�a_�s_�o_�n_�s _�t_�o _�B_�o_�x _�P_�r_�i_�m_�i_�t_�i_�v_�e _�T_�y_�p_�e_�s

       What good is all of this?

       Makes conceptual sense to programmers used to object interfaces as _�t_�h_�e
       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

       Perl is an idiomatic language and this is an important idiom.

       _�S_�u_�b_�j_�e_�c_�t _�F_�i_�r_�s_�t_�: _�A_�n _�A_�s_�i_�d_�e

       Perl's design philosophy promotes the idea that the language should be
       flexible enough to allow programmers to place the  of a statement
       first.  For example, "die $! unless read $file, 60" looks like the pri-
       mary 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)".

       _�A_�u_�t_�o_�b_�o_�x_�i_�n_�g _�a_�n_�d _�M_�e_�t_�h_�o_�d _�R_�e_�s_�u_�l_�t_�s

       In Chapter 11 [Subroutines], we had examples of ways an expression
       could be written.  Here it is again:

         # 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.

       _�P_�e_�r_�l_�6_�:_�:_�C_�o_�n_�t_�e_�x_�t_�s recognizes object context as provided by "->" and
       coerces %hash and @array into references, suitable for use with _�a_�u_�t_�o_�-
       _�b_�o_�x.  (Note that _�a_�u_�t_�o_�b_�o_�x also does this automatically as of version
       2.40.)  _�a_�u_�t_�o_�b_�o_�x associates primitive types, such as references of vari-
       ous sorts, with classes.  _�a_�u_�t_�o_�b_�o_�x_�:_�:_�C_�o_�r_�e throws into those classes meth-
       ods wrapping Perl's built-in functions.  In the interest of full dis-
       closure, _�P_�e_�r_�l_�6_�:_�:_�C_�o_�n_�t_�e_�x_�t_�s and _�a_�u_�t_�o_�b_�o_�x_�:_�:_�C_�o_�r_�e are my creations.

       _�A_�u_�t_�o_�b_�o_�x _�t_�o _�S_�i_�m_�p_�l_�i_�f_�y _�E_�x_�p_�r_�e_�s_�s_�i_�o_�n_�s

       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 charac-
       ters.  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 bro-
       ken 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

       This could also have been written:

         sub { CGI::param($_[0]) }->map(@cgi_vars)  # turn CGI arg names into values
                  ->join("\n")                      # join with newlines
                  ->concat("\n")                    # give it a trailing newline
                  ->print;                          # print them all out

       "map()" is .  The "map()" method defined in the "autobox::Core::CODE"
       package takes for its arguments the things to map.  The "map()" method
       defined in the "autobox::Core::ARRAY" package takes for its argument a
       code reference to apply to each element of the array.

       _�H_�e_�r_�e _�e_�n_�d_�s _�t_�h_�e _�t_�e_�x_�t _�q_�u_�o_�t_�e_�d _�f_�r_�o_�m _�t_�h_�e _�P_�e_�r_�l _�6 _�N_�o_�w _�m_�a_�n_�u_�s_�c_�r_�i_�p_�t_�.

       Yes. Report them to the author,  The API is not yet
       stable -- Perl 6-ish things and local extensions are still being

       Version 0.7 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.

       Version 0.6 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 documen-
       tation needs to be updated and mention of Perl6::Contexts mostly
       removed.  Also, JJ contributed a "strip" method for scalars - thanks

       Version 0.5 has an $arrayref->unshift bug fix and and a new flatten
       method for hashes.  Also, this version is untested because my
       Hash::Util stopped working, dammit.

       Version 0.4 got numeric operations, if I remember.

       Version 0.3 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!  Version
       0.3 also added the references to Perl 6 Now and the excerpt.

       Version 0.2 rounded out the API and introduced the beginnings of func-
       tional-ish methods.

       Version 0.1 was woefully incomplete.

       Copyright (C) 2009, 2010 by Scott Walters

       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.

       Perl 6: <>.
       (Shameless plug:) _�P_�e_�r_�l _�6 _�N_�o_�w_�: _�T_�h_�e _�C_�o_�r_�e _�I_�d_�e_�a_�s _�I_�l_�l_�u_�s_�t_�r_�a_�t_�e_�d _�w_�i_�t_�h _�P_�e_�r_�l _�5
       dedicates a sizable portion of Chapter 14, Objects, to autoboxing and
       the idea is used heavily throughout the book. Chapter 8, Data Struc-
       tures, also has numerous examples. See <> or look
       for ISBN 1-59059-395-2 at your favorite bookstore for more information.

       Scott Walters,  Also, JJ contributed a "strip"
       method for scalars - thanks JJ!  (Is it wrong to cut and paste documen-
       tation?)  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.

perl v5.8.9                       2010-03-04                  autobox::Core(3)
Something went wrong with that request. Please try again.