$text = "A'B'C" ; $text = replacequote($text); print $text; sub replacequote { my $X=$_[0]; while ( $X =~ /\'/ ) { (my $l, my $r) = split ( /\'/, $X, 2); $X = "$l\\QUOTE$r"; } while ( $X =~ /\\QUOTE/ ) { (my $l, my $r) = split ( /\\QUOTE/, $X, 2); $X = "$l\\'$r"; } return $X; } sub replacequote_better { my $X=$_[0]; while ( $X =~ /[^\\]\'/ ) { #This line does not give the desired result that I have in mind (l remains empty): (my $l, my $r) = split ( /[^\\]\'/, $X, 2); #print "left: $l\n"; #print "right: $r\n"; @array = split ( /[^\\]+\'/, $X, 2); print $_, "|" foreach @array; print "\n" ; $X = "$l\\'$r"; #print "new $X\n" ; } return $X; }