\n is only converted to newline when it's seen in a string literal by the perl compiler. The compiler doesn't see \n in your example, just $1.
The following makes the compiler see it (by compiling the match everytime one is found):
warn 'tab' if unescape("\\t") eq "\t"; warn 'nl' if unescape("\\n") eq "\n"; warn 'bel' if unescape("\\07") eq "\07"; sub unescape { my($s)=@_; $s =~ s/(\\[^\d])/ (eval "\"$1\"") || $1 /ge; # "\t", "\n", etc $s =~ s/\\(0\d+)/ eval "chr($1)" /ge; # "\07", etc. return $s; }
It's more efficient to do the logic yourself:
my %SLASHED = ( t => "\t", n => "\n", r => "\r", ); warn 'tab' if unescape("\\t") eq "\t"; warn 'nl' if unescape("\\n") eq "\n"; warn 'bel' if unescape("\\07") eq "\07"; sub unescape { my($s)=@_; $s =~ s/\\([^\d])/ $SLASHED{$1} || $1 /ge; # "\t", "\n", etc. $s =~ s/\\0(\d+)/ chr(oct($1)) /ge; # "\07", etc. return $s; }
Both solutions are untested.
In reply to Re: Unable To Replace Escape Sequences With 1-Char Equivalents
by ikegami
in thread Unable To Replace Escape Sequences With 1-Char Equivalents
by williams
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |