foreach my $ref (sort substr($a,1) <=> substr($b,1) if $substr($ref, 0,1) eq 'A' @tempArray){ ...do whatever... }