I know, this is the most diffucult mode but...
i like this construct and i post it
My task:
I have a gene sequence like

aaaaaxxxxxaaaaaaxxxxxxxxaaaaxxxx

where a=intron x=exons (different regions of a gene)
i use this routine to count the regions a and x
and store it in an array of array:
finally i have something like:
$region[0]=[a, 123]
where the first element is the type and the second element is the length. the counter use an hash, an array some others data structure to take counts of elemants... here is the code:

sub catch_exons { my $dna = $_[0]; my @dna = split (//, $dna); my %seen = (); my $i=0; my $a; my $x; my @region; my $nt; # first split sequemnce in char # with seen{a} and seen {x} take count of the last letter # with $a and $x take count of intron and exon length # @region is a complex data strucure (array of array) that store: +a or x (intron and exon) and legth foreach $nt (@dna) { $i++; chomp $nt; if ($nt eq 'a') { if (!defined $seen{x} and !defined $seen{a}) { $seen{a} = 0; $a = 1; } elsif (!defined $seen{a} and defined $seen{x}) { $seen{a} = 0; #defined $seen{x} = undef; push (@region, ['x',$x]); $a = 1; } else { $a++; } } if ($nt eq 'x') { if (!defined $seen{a} and !defined $seen{x}) { $seen{x} = 0; $x = 1; } if (!defined $seen{x}) { $seen{x} = 0; #defined $seen{a} = undef; push (@region , ['a',$a]); $x = 1; } else { $x++; } } } if (defined $seen{a}) { push (@region, ['a', $a]); } elsif (defined $seen{x}) { push (@region, ['x', $x]); } return (@region); };

Hope that it will be useful for someone!

20040722 Edit by castaway: Changed title from 'exercise I'

janitored by ybiC: Balanced <readmore> tags around longish codeblock, to reduce scrolling

Replies are listed 'Best First'.
Re: counting gene regions
by ccn (Vicar) on Jul 21, 2004 at 12:13 UTC

    this code does the same: :)

    sub catch_exons2 { my @res; push @res, [substr($1, 0, 1), length $1] while $_[0] =~ /(a+|x+)/g +; return @res; }

    Upd or even without a sub:

    $string = 'aaaaxxxaxaxaaaaaaaxxxxxxxxxxaax'; @regions = map { [substr($_, 0, 1), length $_] } $string =~ /(a+|x+)/g +;

    Update: s/\$1/\$_/g in the last onliner

      realy cool and sintetic, i will update my code soon!
      I know, i write a lot :-)!