Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use autobox in Perl?

Tags:

perl

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 evals (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?

like image 430
Robert P Avatar asked Oct 05 '09 18:10

Robert P


3 Answers

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.

like image 127
Sinan Ünür Avatar answered Nov 15 '22 15:11

Sinan Ünür


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/

like image 21
draegtun Avatar answered Nov 15 '22 16:11

draegtun


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.

like image 34
jrockway Avatar answered Nov 15 '22 16:11

jrockway