G'day FIJI42,
Biological data are typically huge.
For reasons of efficiency, when dealing with this type of data, you should choose a fast solution over a slower one.
Perl's string handling functions
(index, substr, etc.)
are measurably faster than regexes (try it yourself with Benchmark).
String operators (e.g. $x eq 'some literal') will be far more efficient
than an equivalent regex (e.g. $x =~ /^some literal$/).
There are times when you will need a regex.
In these cases, don't give the regex more work than necessary.
In "/(AA)/gi", you're asking it to pointlessly capture matches (you never use the captured data);
and you're also asking for a case-insensitive match (again pointless, as all characters are uppercase).
Where you are dealing with mixed-case, or unknown case, canonicalise your data once then work with that
(see fc,
uc, and lc).
With your specific question, index would be the best choice.
Your ultimate goal is somewhat unclear.
If you want to match "AA" once in "AAA", and twice in "AAAA":
$ perl -E '
my ($x, $y, $c, $p) = qw{AxAAxAAAxAAAA AA 0 0};
$c++, $p += 2 while ($p = index $x, $y, $p) > -1;
say $c;
'
4
If you want to match "AA" twice in "AAA", and thrice in "AAAA":
$ perl -E '
my ($x, $y, $c, $p) = qw{AxAAxAAAxAAAA AA 0 0};
$c++, $p++ while ($p = index $x, $y, $p) > -1;
say $c;
'
6
Note that the only difference between those two is:
in the first, the position ($p) is incremented by two ($p += 2);
in the second, it is incremented by one ($p++).
That code is really only about quickly demonstrating the index function.
It's not intended as a production-grade solution; for instance, pick better (more meaningful) variable names.
|