This is an object method that I wrote to paginate data in an array.
sub paginate {
# usage: my $indices = $obj->paginate($records,$per_page,$page);
#
# parameters: $records = numeric, number of records (scalar @results,
+for example)
# $per_page = numeric, how many records to display per page
# $page = numeric, what page we're currently on
#
# return values: fail = empty array
# success = array or array ref of indicies to use with the original @
+results
# example: @results[@indices] or @results[@$indices]
my $self = shift;
my ($records,$per_page,$page) = @_;
my $indices;
# record count is required, can't make it up
return (wantarray ? () : []) unless ($records && $records =~ /^\d+
+$/);
# defaults for others
$per_page ||= 10;
$page ||= 1;
# calcuate last page
my $last_page = int($records / $per_page);
$last_page++ if ($records % $per_page);
# page safeguards
$page = 1 if ($page < 1 || $page > $last_page);
# calculate offset, starting with 0
my $offset = ($page - 1) * $per_page;
########################
### results per page ###
########################
if ($offset + $per_page <= $records) {
# normal operation
$indices = [$offset .. $offset + $per_page - 1];
} else {
# don't go past the end of the array!
$indices = [$offset .. $records - 1];
}
return wantarray ? @$indices : $indices;
}
Update: I just noticed I basically reinvented
Data::Page. Doh! I find it funny that the author of that module and I even use the same parameters, and in the same order. From the docs:
my $page = Data::Page->new($total_entries, $entries_per_page, $current_page);
---
It's all fine and dandy until someone has to look at the code.