# Get all combinations of (seg_dtl_id,pan_id) for seg_id=1 $sql = <query($sql); # Remember previous dtl_id so we can tell to start a new line my $prev_dtl_id; foreach (@$rs) { my ($dtl_id, $pan_id) = @$_; if ($dtl_id ne $prev_dtl_id) { # Only start a new line if we're not on first dtl_id print FILE "\n" if defined $prev_dtl_id; print FILE "$dtl_id: "; $prev_dtl_id = $dtl_id; } print FILE "$pan_id|"; }