>>>>> "PL" == Paul Lalli <> writes:
PL> A coworker just presented me with this task. I came up with two
PL> solutions, but I don't like either of them. He has a text document
PL> and wants to scan it for characters such as newline, tab, form feed,
PL> carriage return, vertical tab. If found, he wants to replace them
PL> with their typical representation (ie, \n, \t, \f, \r, \v).
PL> I first gave him the obvious:
PL> $string =~ s/\n/\\n/;
PL> $string =~ s/\t/\\t/;
PL> $string =~ s/\f/\\f/;
PL> $string =~ s/\r/\\r/;
PL> $string =~ s/\v/\\v/;
PL> which I don't like because of how much copy/paste is involved. Then I
PL> came up with:
use a hash table for the conversion:
my %controls = (
"\n" => '\\n',
"\t" => '\\t',
"\r" => '\\r',
"\f" => '\\f',
"\v" => '\\v',
) ;
$string =~ s/([\n\t\r\f\v])/$controls{$1}/g;
and if you want to get anal about dups of the chars do this:
my @controls = qw( n t r f v ) ;
my %control_to_escape = map { eval( "\\$_" ) => "\\$_" } @controls ;
my $controls_re = '[' . join( '', map "\\$_", @controls ) . ']' ;
$string =~ s/($controls_re)/$controls_to_escape{$1}/g;
see ma! only one use of the actual control letters!
uri
--
Uri Guttman ------
--------
http://www.sysarch.com --
----- Perl Code Review , Architecture, Development, Training, Support ------
--------- Gourmet Hot Cocoa Mix ----
http://bestfriendscocoa.com ---------