Perl - Avoiding / Encoding Special Characters

I am writing a script for IRC, and sometimes I may need to use color. I usually do it like this.

my $C = chr(3); 

$C is the control code used for color, but I saw another script that escapes something like "\ x \ v ...". How to get the correct encoded version? I tried Data::Dumper , but I did not find it. Hope this question makes sense.

+4
source share
4 answers

The way to specify chr(3) with the 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 :

In constructs that interpolate and transliterate, the following escape sequences are available.

  • \t tab (HT, TAB)
  • \n newline (NL)
  • \r return (CR)
  • \f feed feed (FF)
  • \b backspace (BS)
  • \a alarm clock (bell) (BEL)
  • \e escape (ESC)
  • \033 octal char (example: ESC)
  • \x1b hex char (example: ESC)
  • \x{263a} wide hex char (example: SMILEY)
  • \c[ char control (example: ESC)
  • \N{name} named Unicode
+5
source

Characters with codes in the range 0 .. 255 can be expressed in several ways. In this example, all type the character A :

 print chr(65); print "\101"; # octal notation print "\x41"; # hexidecimal notation (and hexadecimal notation) printf "%c",65; 


or for your specific problem:
 print chr(3); print "\003"; print "\3"; print "\x03"; # hexidecimal notation (and hexadecimal notation) printf "%c",3; print "\cc"; # from Sinan answer print "\cC"; 
+5
source

You can print hexadecimal (or even octal or binary encoded) characters using a number of mechanisms (and this is by no means a complete list):

 # generate strings from hex: my $space_char = sprintf("%x", 0x20); my $space_char2 = "\x20"; my $space_char3 = 0x20; my $space_char4 = pack("L", 0x20); my $space_char5 = chr(0x20); 

You can read about these functions in perldoc perlfunc or individually through perldoc -f sprintf , perldoc -f pack , perldoc -f chr , etc.

For more information on hexadecimal, octal, and binary numbers in general, see "Scalar Value Constructors" in the perldoc perldata section.

+3
source

See the Escape sequence sections and Character classes and other special screens in perldoc perlre .

+1
source

Source: https://habr.com/ru/post/1303276/


All Articles