in reply to Remember previous element in a loop

Maybe I don't understand: the only thing your code seems to miss is the thing you want to assign to $prev which should be presumably $x or something obtained in connection with it. OTOH you iterate over that $x but appear not to use it at all. And as a side note chances are that your code is not strict safe, although you may have my $x; in a part of your program you do not show... but even in that case I would recommend scoping as closely as possible instead!

Also, all in all perl-style for loops are preferrable over C-style ones, but in this case I think it's customary to do

while (my $data = $sth->fetchrow_hashref) { # ...

instead.