views:

66

answers:

2

I have a Perl script that replaces any Us or Ns at the end of a string with Ts. This program is what I'm trying:

use strict;
my $v = "UUUUUCCNNCCCCNNNCUUUNNNNN";
printf("before: %s \n", $v);
if($v =~ m/([UN]+)$/)
{
  my $length = length($1);
  substr($v, (length($v) - $length), $length) = "T" x $length;
}
printf(" after: %s \n", $v);

It produces this output:

> ./test
before: UUUUUCCNNCCCCNNNCUUUNNNNN 
 after: UUUUUCCNNCCCCNNNCTTTTTTTT

Is there any way of doing this with a single regular expression, translation, or other command?

+8  A: 

    $v =~ s/([UN]+)$/'T' x length($1)/e;

The /e modifier instructs Perl to treat the replacement clause 'T' x length($1) as an expression to be evaluated, and to use the result of the evaluation as the replacement string.

mobrule
Awesome, that works. Thanks!
Daniel Standage
+4  A: 

For the sake of TIMTOWTDI:

$v =~ s/[UN](?=[UN]*$)/T/g;
Boocko