2

I'm pretty new to Perl so pardon me for what will probably turn into a most obvious answer.

I'm trying to pass a Unicode markup to the chr() function. Here's a redacted example of my script.

#!/usr/bin/perl
$unicode = "/u0026amp;";
print chr("0x".substr($unicode, 4, 2))."\n";

This properly extracts the 26 from the $unicode variable. However the problem as I can tell is that the chr() function doesn't like quoted strings, but if I remove the quotes the x in 0x gets removed and becomes an invalid 026 rather than a valid 0x26.

Anyways, this really gets down to. How can I keep the x in

chr("0x".substr($unicode, 4, 2))

from disappearing and send the proper 0x26

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Aurelius
  • 23
  • 3

1 Answers1

3

You do not use "0x" strings with chr, the way you can with ord and hex. So you want:

 chr(hex($hexstring))
tchrist
  • 78,834
  • 30
  • 123
  • 180
  • Thank you very much! This was spot on. I'm still not sure why directly using 0x26 works but not through passing or concatenation. Edit: I should mention my final solution was: chr(hex(substr($unicode, 4, 2))) – Aurelius Apr 22 '11 at 17:05
  • @Aurelius: Because the rules for numeric literals like 0x26 or 046 or 0b100110 or 186_242 are not the rules used for converting strings into numbers, which are much stricter and decimal only. – tchrist Apr 22 '11 at 17:18