#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @nlist = qw( 3 24 8 17 23 14 17 9 16 24 25 11 22 14 14 8 19 16 15 8 ); my @key_list = ( 'A' .. 'Z' ); my %hoa; foreach my $num ( @nlist ) { my $key; foreach my $check_key ( @key_list ) { if( not exists $hoa{ $check_key } or $num % $hoa{ $check_key }[ 0 ] == 0 ) { $key = $check_key; last; } } die "Key list depleted" if not defined $key; push @{ $hoa{ $key } }, $num; } print Dumper \%hoa;