my %data = (); # get the data while () { my @fields = split; # get fields my $key = pop @fields; # remove rightmost my $line = [@fields]; # $line is ref to list of fields push @{$data{$key}}, $line; # add to list of lines, in hash } close TEMP; #now print it: foreach my $key (sort keys %data); { print "$key\n"; my @lines = @{$data{$key}}; # list of lines, from hash foreach my $line (@lines); { my @fields = @$line; # list of fields, from array-ref my $text = join(" ", @fields); print "$text\n"; } print "\n"; }