Sorry, but your code is not runnable, and doesn't seem to be representative of the problem you're having. Please see How do I post a question effectively?, I know what I mean. Why don't you?, and Short, Self-Contained, Correct Example.
This is a guess of what you want that I've pieced together from your various posts.
use warnings;
use strict;
use Data::Dump;
use DBI;
my $titlesperpage = 10;
# set up a dummy database
my $dbh = DBI->connect("dbi:SQLite::memory:", undef, undef,
{ RaiseError=>1 });
$dbh->do(<<'END');
CREATE TABLE messages (
msgID INTEGER,
threadID INTEGER
)
END
my $sth_i = $dbh->prepare(
'INSERT INTO messages (msgID, threadID) VALUES (?,?)');
$sth_i->execute($_,$_>>4) for 0..127;
for my $currentpage (1..5) { # simulate requests for different pages
my $startcount = ($currentpage - 1) * $titlesperpage + 1;
my $stopcount = $currentpage * $titlesperpage;
dd $startcount, $stopcount;
my $sth_s = $dbh->prepare('SELECT msgID, threadID FROM messages');
$sth_s->execute;
my %threadIDs;
my $rowcnt = 1;
while ( my $row = $sth_s->fetchrow_hashref ) {
$threadIDs{ $row->{threadID} }++;
if ( $rowcnt >= $startcount && $rowcnt <= $stopcount ) {
dd $row->{msgID};
}
} continue { $rowcnt++ }
dd \%threadIDs;
}
But this loops through all results for every request. You can have the database do the pagination, even though you have to hit the database twice it still doesn't require you to loop through all records, only those for the current page.
for my $currentpage (1..5) { # simulate requests for different pages
my $startcount = ($currentpage - 1) * $titlesperpage + 1;
dd $dbh->selectall_arrayref(
'SELECT threadID, COUNT(*) FROM messages GROUP BY threadID');
my $sth_s = $dbh->prepare('SELECT msgID, threadID FROM messages '
.'ORDER BY msgID LIMIT ?,?');
$sth_s->execute($startcount, $titlesperpage);
while ( my $row = $sth_s->fetchrow_hashref ) {
dd $row->{msgID};
}
}