my %grouped; while (...) { my @fields = ...; push @{ $grouped{$fields[0]} }, \@fields; } for my $group (values %grouped) { ... }