# Use an HoH instead of simple array my %categories; foreach (@sub) { $categories{length($_)}{$_} = undef; } # ... when you need it... sub matches_any { my $t = shift; foreach my $len (keys %categories) { # We could also sort here... return 1 if exists $categories{$len}{substr($t, 0, $len)}; } return 0; }