in reply to Count every 3rd base occurence

Here is my solution:

use strict; use warnings; my $string = "CTCCGGATCTAT"; my $sets = length($string)/3; # we want to know how man +y sets of 3 there are my $unpacker = 'A3' x $sets; # create our unpack templ +ate my @dna = unpack($unpacker, $string); # create the array of set +s my $counter = 0; # initialize the counter for my $set (@dna) { # for each $set in @dna d +o... my $check = substr($set, 2, 1); # get the 3rd char of the + $set ++$counter if ($check =~ /[GC]/i); # increment the counter, +ignore case } print "$counter/$sets was either C or G.\n"; # print results

Replies are listed 'Best First'.
Re^2: for loops
by Aristotle (Chancellor) on Dec 16, 2002 at 20:30 UTC
    Why so complicated?
    use strict; use warnings; my $string = "CTCCGGATCTAT"; my $counter = 0; $counter++ while $string =~ /..[GC]/gi; print "Found $counter occurences$/";
    Oops, duh. I even tested. %-/
    use strict; use warnings; my $string = "CTCCGGATCTAT"; my %flag = (C => 1, G => 1, A => 0, T => 0); my $counter = 0; $counter += $flag{$1} while $string =~ /..(.)/g; print "Found $counter occurences$/";

    Makeshifts last the longest.

      Ugh, had to read BrowserUk's approach twice to see what was going on. Mine isn't as simple as it started out either - raaa, so obvious in hindsight: my $count = grep /[GC]/, $dna =~ /..(.)/g; There. It slices, it dices, it counts DNA bases. (Or is that RNA? Anyway.)

      Makeshifts last the longest.

        Much better than mine, and any of the others to my way of thinking, Clean, neat and obvious (to read).

        Should have been obvious to write too, but it wasn't.


        Examine what is said, not who speaks.

      Why so complicated? ;)

      my $count=0; $count += substr($dna, $_, 1) =~ /[CG]/ for map 3 * $_, 1 .. length($d +na)/3; print $count;

      Examine what is said, not who speaks.

      Why so complicated?

      1. TIMTOWTDI
      2. The comments shed light on how it works
      3. It worked the first time. q-:
      4. Why not?