Box::Limited - Box with a limited capacity.
This class represents a box which can contain only a limited number of items with a limited total weight. This can be useful e.g. to form requests to a certain API which has a limit on the number of items / total characters sent within one request.
use Box::Limited; use List::Util qw(sum0); my $box = Box::Limited->new( size => 100, max_weight => 200, weight_function => sub (@items) { # "Weight" of item is a length of its string form in this case return sum0 map { length($_) } @items; }, ); while (my $item = shift @items) { if ($box->can_add($item)) { $box->add($item); } else { say "Box is full"; # ...process full box... } }
Box size - the maximum amount of items the box can hold. Non-negative integer; required.
Maximum weight of all items in the box. Non-negative integer; required.
Code reference of weighting function; required. Its argument is an array of items, and return value must be an integer representing weight of all items.
Whether $item can be added to the box. $item is any scalar that can be weighted by weight_function.
$item
weight_function
Adds $item to the box and returns true. If item cannot be added, raises exception.
Returns array of items in the box in the same order they were added there.
Returns number of items in the box.
Whether the box is empty or not.
Clears the box and returns true.
In: \%constructor_arg - constructor arguments (all the attributes required for new()) Out: @filled_boxes - array of boxes filled with @items
Class method. Creates as many boxes as required to put all the @items in them, puts items there and returns boxes.
@items
Items are processed in the order they were passed - there is no heuristic to minimize the total number of used boxes.
Ilya Chesnokov chesnokov@cpan.org.
Under the same terms as Perl itself.
Thanks to Perceptyx, Inc for sponsoring work on this module.
To install Box::Limited, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Box::Limited
CPAN shell
perl -MCPAN -e shell install Box::Limited
For more information on module installation, please visit the detailed CPAN module installation guide.