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.

In reply to Re: SQL Paging with Perl by kwaping
in thread SQL Paging with Perl by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.