use Data::Dumper; my %hash; my $sub_length = '.' x 2; while () { chomp; # remove the chomp. It's unnecessary $hash{$.-1}=[ grep /$sub_length/o, split /($sub_length)/o ]; } print Dumper \%hash; __DATA__ ABDC EFGH #### use Data::Dumper; my %hash; my $sub_length = '.' x 2; $hash{$.-1}=[ grep /$sub_length/o, split /($sub_length)/o ] while ; print Dumper \%hash; __DATA__ ABDCX EFGHX