The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Box::Limited - Box with a limited capacity.

DESCRIPTION

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.

SYNOPSIS

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

        }
    }

ATTRIBUTES

size

Box size - the maximum amount of items the box can hold. Non-negative integer; required.

max_weight

Maximum weight of all items in the box. Non-negative integer; required.

weight_function

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.

METHODS

can_add($item)

Whether $item can be added to the box. $item is any scalar that can be weighted by weight_function.

add($item)

Adds $item to the box and returns true. If item cannot be added, raises exception.

items

Returns array of items in the box in the same order they were added there.

items_count

Returns number of items in the box.

is_empty

Whether the box is empty or not.

clear

Clears the box and returns true.

split_to_boxes(\%constructor_arg, @items)

    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 are processed in the order they were passed - there is no heuristic to minimize the total number of used boxes.

AUTHOR

Ilya Chesnokov chesnokov@cpan.org.

LICENSE

Under the same terms as Perl itself.

CREDITS

Thanks to Perceptyx, Inc for sponsoring work on this module.