while (my $r = $attr_detail->fetchrow_hashref()) { $details->{$r->{'masterid'}}->{$r->{pco_attribute_id'}}->{pco_value} = $r->{'pco_value'}; } # ... while (my ($master_id, $attr_ref) = each %details) { while (my ($attr_id, $pco_value) = each %$attr_ref) { print DETAILS "$master_id\t$attr_id\t$pco_value\n"; } }