cool use for map

nkuipers nkuipers at uvic.ca
Wed Oct 30 11:40:17 CST 2002


well, it may be a vagary of activestate perl, but when I ran this:

@array = map {$1} 'aagctGGGGTCAGAtttttacGCATCAaa' =~ m/([A-Z]+)/g;
print "Found $_\n" for @array;

I got

Found GGGGTCAGA
Found GCATCA

although I agree it's more complex than

@found = $searchthis =~ /($forthis)/g;

wierd.

>===== Original Message From Peter Scott <Peter at PSDT.com> =====
>At 07:22 PM 10/29/2002 -0800, nkuipers wrote:
>>@found = map { $1 } $searchthis =~ m/($forthis)/g;
>
>Um, I do not think this does what you intend.  It gives you a copy of the
>last $1 for each match:
>
>% perl -le '@x = map { $1 } "ab12cd3f g" =~ /([a-z])/g; print join " * ", @x'
>g * g * g * g * g * g
>
>Whereas if you do
>
>   @found = $searchthis =~ /($forthis)/g;
>
>since the result of a /g match in list context is the list of all capturing
>parentheses matches, you get
>
>%  perl -le '@x = "ab12cd3f g" =~ /([a-z])/g; print join " * ", @x'
>a * b * c * d * f * g
>
>which seems considerably more useful... and less obscure.
>
>>As written, it's not terribly useful unless you are interested in how many
>>times $forthis matches and put @found in scalar context.  But if you
>>substitute a quantified character class for $forthis, suddenly you are
>>extracting from a sequence all runs of hydrophobic amino acid residues,
>>lowercase nucleotides, and so forth, all in one line.  I didn't think you
>>could use a regex as the list context construct in map, but decided to try 
it
>>rather than rolling another clunky "while matches push array and return once
>>finished".  Actually it's part of a method that maps to @found differently
>>using if-elsif-elsif... so the one-lining is much nicer on the eyes.  Yay
>>Perl.
>
>Peter Scott
>peter at psdt.com
>http://www.perldebugged.com




More information about the Victoria-pm mailing list