foreach $element (@dports) { $count_hash{$element}++; } foreach $key (@predefined) { print "$key\n" x $count_hash{$key} if $count_hash{$key}; }