miketosh has asked for the wisdom of the Perl Monks concerning the following question:

I'm looking for a simple way to output the escaped-values of certain control characters, such as carriage return and line feed.

Code:
my $string = "1\r\n 2 \n"; while ($string = /(.)/g) { print "Encountered character: $1\n"; }
My Desired output for the above code would be:
Encountered character: 1 Encountered character: \r Encountered character: \n Encountered character: \s Encountered character: 2 Encountered character: \s Encountered character: \n
Are there any known ways to get those values converted?

Replies are listed 'Best First'.
Re: Printing escaped values of control characters
by Eliya (Vicar) on Aug 02, 2011 at 15:40 UTC

    Just create a lookup table for whatever characters you consider to be control characters (why is space a control char?):

    my %escaped = ( "\n" => '\n', "\r" => '\r', " " => '\s', # ... ); my $string = "1\r\n 2 \n"; while ($string =~ /(.)/sg) { my $ch = $1; $ch = $escaped{$ch} if exists $escaped{$ch}; print "Encountered character: $ch\n"; }
Re: Printing escaped values of control characters
by Jim (Curate) on Aug 02, 2011 at 15:41 UTC

    Use a simple lookup table—a hash—you initialize yourself.

    By the way, \s is not a character escape sequence; it's a regular expression pattern escape sequence. There's no general, one-to-one pairing of characters with regex patterns.

Re: Printing escaped values of control characters
by johngg (Canon) on Aug 02, 2011 at 22:44 UTC

    Using a lookup as suggested by Eliya and Jim but instead of using a regex capture it seems simpler to just split into individual characters and feed into a map doing a lookup in a ternary.

    knoppix@Microknoppix:~$ perl -E ' > %esc = ( > qq{\n} => q{\n}, > qq{\r} => q{\r}, > q{ } => q{\s}, > ); > $str = qq{1\r\n 2 \n}; > say qq{Saw $_} for > map { exists $esc{ $_ } ? $esc{ $_ } : $_ } > split m{}, $str;' Saw 1 Saw \r Saw \n Saw \s Saw 2 Saw \s Saw \n knoppix@Microknoppix:~$

    I hope this is helpful.

    Cheers,

    JohnGG

Re: Printing escaped values of control characters
by perl5ever (Pilgrim) on Aug 02, 2011 at 20:17 UTC
    You can use Data::Dumper with Useqq(1):
    use Data::Dumper; sub to_string { Data::Dumper->new([])->Terse(1)->Indent(0)->Useqq(1)->Values([$_[0]] +)->Dump; } say to_string(chr(13)); # "\r" say to_string(chr(10)); # "\n" say to_string(chr(97)); # "a" say to_string(chr(31)); # "\37"