my $section = ''; while (my $row = $sth->fetchrow_hashref) { my $prefix = substr($row->{name}, 0, 2); if ($prefix ne $section) { $section = $prefix; print qq{$section}; } # do the usual }