For those unaware of Perl's autobox
, it is a module that gives you methods on built in primitives, and lets you even override them.
# primitives
'a string'->toupper();
10->to(1); # returns [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
# Arrays, array refs
[qw(A B C D E)]->for_each( sub { ... } );
@array->length()
# Hashes, hash refs
{ key => 'value', key2 => 'value2' }->values()
%hash->keys()
# Even specify your own base class...
use autobox SCALAR => 'Foo';
It overall makes methods on built in types feel more like objects, simplifying some tasks and making others seem more obvious.
However...
the autobox
docs say that there's performance penalties, some more than simply calling the method on the object, much more than the standard syntax. And then, there's a few caveats about its use in eval
s (specifically, string evals) that might, in some circumstances, cause issues. It also looks like it doesn't come standard with many Perl distros.
Is it ever really worth it to use autobox?
Well, did you ever wish there were a module that did what autobox does before you found out about autobox?
If the answer is 'yes', then you should use it. You might also want to contribute to its development by filing bug reports and fixing them if you get the opportunity.
Unfortunately, I fall into the camp of 'cool, but ...' so I cannot offer you any more insight.
Horses for courses! However reading a chain from left to right is often easier to grok IMHO:
say sort grep /\w/, map { chr } 0 .. 255;
While shorter below does flow nicer:
say [ 0..255 ]->map( sub { chr } )->grep( sub { m/\w/ } )->sort->join('');
ref: snippet from Hacker News comments
/I3az/
I use autobox for:
$c->login($c->req->{params}->hslice([qw/username password/])
This ends up taking an arbitrary hash and reduces it to { username => <whatever>, password => <whatever> }
. Normally a lot of code. One symbol with Moose::Autobox.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With