in reply to The nth occurrence of a character
my %hash; my @split = split //, $string; my @positions = map { [$split[$_], $_] } 1 .. @split-1; undef @split; foreach (@positions){ push @{$hash{$_->[0]}}, $_->[1]; } undef @positions ;
now, for each character you have a hash entry with all its positions in the string (array).
if for example you want to get the 3rd occurance of 'A', you will simply need to access: $hash{A}[2]
(2 will be the 3rd index in the array)
You wannted efficient function, and this way allows you to get you data in one hash+array access which IMHO is efficient.
the price you will pay is the one-time building of the hash (per string).
Enjoy,
Mickey
|
|---|