in reply to SQL Paging with Perl

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.

Replies are listed 'Best First'.
Re^2: SQL Paging with Perl
by zentara (Cardinal) on Oct 05, 2006 at 16:24 UTC
    Doh! I find it funny that the author of that module and I even use the same parameters, and in the same order.

    I often think about that when I hear about patent lawsuits, and the oft-quoted line "There is no stopping an idea whose time has come" (Victor Hugo?). When you consider that most of us are put through the same basic learning system, are bombarded daily with the same media, and have similar western philosophical minds, it definitely changes the odds that people will write identical code phrases.


    I'm not really a human, but I play one on earth. Cogito ergo sum a bum