#!/usr/bin/perl use strict; use warnings; use Data::Dumper qw/Dumper/; my @array; $array[0] = 'JHON 21 3999999 SCHOOL 1982-05-08'; $array[1] = 'JEFF 21 3999999 SCHOOL 1983-01-09'; my $current = undef; my $prev = undef; my %filtered = (); foreach my $_array (@array){ my @split = split(/\s/, $_array); if (defined $filtered{$split[1]}{$split[4]}) { substr($filtered{$split[1]}{$split[4]},0,1) = (++substr($filtered{$split[1]},0,1)); } else { $filtered{$split[1]}{$split[4]} = "1\t$split[1]\t$split[2]"; } } print Dumper( \%filtered );