Mugiwara
Mugiwara

Reputation: 906

How can I paginate a Perl array?

I don't know if the question is clear or not, anyway, I am reading some data from my google drive spreadsheet using Net::Google::Spreadsheet, and i fetch all the rows in an array as follow my @rows = $worksheet->rows, however, I want to ... let say divide @rows between other arrays, for example @rows has 200 elements, i want to give the first 50 to @array1 and the next 50 to @array2 and so on without using a counter (counter++; if (counter > 50) ...). Or let say i just want to get the elements between 70 and 110 for example.

Upvotes: 2

Views: 468

Answers (2)

Ashley
Ashley

Reputation: 4335

The plain array slice answer is great. I just want to increase visibility of another (class/style of) solution, specifically Data::Page.

It has been said before that this code is "too simple" for CPAN, but I must disagree.

It can seem like overkill but it makes the stuff clean, predictable, and repeatable. When code starts to grow past the one-off stage, it can help quite a lot.

use strictures;
use Data::Page;

my @stuff = ( "a" .. "z" );

my $pager = Data::Page->new;
$pager->total_entries(scalar@stuff);
$pager->entries_per_page(6); # Arbitrary for demo, pick your own page size.

for my $p ( $pager->first_page .. $pager->last_page )
{
    $pager->current_page($p);
    for my $entry ( $pager->splice(\@stuff) )
    {
        print $entry, " is on page ", $pager->current_page, $/;
    }
}
__END__
a is on page 1
--snip--
z is on page 5

Upvotes: 5

jkshah
jkshah

Reputation: 11713

You could use something like this:

my @array1 = @rows[0 .. 49];
my @array2 = @rows[50 .. 99];

This is referred to as data slicing. Refer to this documentation for more details.

Upvotes: 6

Related Questions