in reply to question about algorithm

Assuming the data is sorted as shown, there's no need for a hash. You just have to keep track of the value from the previous row.
my $prev; while (<$fh>) { my ($field1, $field2) = split; if (!defined($prev) || $prev ne $field2) { print("\n") if !defined($prev); $prev = $field2; print("$field2\n"); } print("$field1\n"); }