Want perl regexp substitution to start over and avoid `1 while` trick

  • A+
Category:Languages

Example: I want to remove duplicate chars in $s like this:

my $s = 'aabbbcbbac'; 1 while $s =~ s/((.).*)/2/$1/; print $s, "/n";                     #prints abc 

Is there a simple and short way to avoid the 1 while trick and remove duplicates with just one s///g? Getting it to "start over" somehow? by using /G or some sort of look-behind|-ahead? Just adding /g is not the solution here.

 


This could be done with a variable-length look-behind, which isn't allowed. But a variable-length look-behind is equivalent to a variable-length look-ahead on the reverse of the input, so we have this trick available:

reverse the string, delete chars using a look-ahead, and reverse again

$t = reverse $s; $t =~ s/(.)(?=.*/1)//sg; $s = reverse $t; 

If you have Perl 5.14 or better and can use the /r modifier on substitutions, you get

$s = reverse( reverse($s) =~ s/(.)(?=.*/1)//grs ); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: