in reply to SQL Paging with Perl
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; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: SQL Paging with Perl
by zentara (Cardinal) on Oct 05, 2006 at 16:24 UTC |