perl

How do I escape/encode special characters in Perl?


I'm writing a script for IRC, and sometimes I might need to use a color. Normally I do it this way:

my $C = chr(3);

$C is the control code used for color, but I've seen some other script that escapes it something like "\x\v...". How do I get the correct encoded version of that? I tried Data::Dumper, but I didn't find it.


Solution

  • The way to specify chr(3) with a hexadecimal escape code is to use:

    print "\x03\n";
    

    or, in octal:

    print "\003\n";
    

    or, as a control code:

    print "\cC\n";
    

    See perldoc perlop:

    The following escape sequences are available in constructs that interpolate and in transliterations.

    1. \t tab (HT, TAB)
    2. \n newline (NL)
    3. \r return (CR)
    4. \f form feed (FF)
    5. \b backspace (BS)
    6. \a alarm (bell) (BEL)
    7. \e escape (ESC)
    8. \033 octal char (example: ESC)
    9. \x1b hex char (example: ESC)
    10. \x{263a} wide hex char (example: SMILEY)
    11. \c[ control char (example: ESC)
    12. \N{name} named Unicode character