Sponsored Content
Top Forums UNIX for Advanced & Expert Users Convert UTF-8 encoded hex value to a character Post 302252183 by cbkihong on Tuesday 28th of October 2008 11:56:06 PM
Old 10-29-2008
Ok, in case you feel bewildered by that manpage (you probably will!), let me give you a series of examples to give you a general idea of some of the most important things you need to know.

As I'm Chinese, I'll use Chinese in the examples. All the code are in UTF-8.

Expected environment: a UTF-8 terminal with proper fonts to render Unicode text.

Test 1 - Let's start with this
Code:
my $str = "你好吗?";

print("$str\n");
printf("Length: %d\n", length($str));

你好吗?
Length: 12

This is made up of 4 Chinese characters, 3 bytes each in UTF-8. So, because Perl does not treat it as UTF-8 but rather ASCII, the length returned is 12. The terminal still renders the string properly because the bytes are returned verbatim to the terminal and the terminal tries to decode the bytestream as UTF-8, remember I assumed the terminal is properly configured to UTF-8 (but not Perl in this case)?

Test 2 - Recognize UTF-8 characters embedded in source code
Code:
use utf8;

my $str = "你好吗?";

print("$str\n");
printf("Length: %d\n", length($str));

Wide character in print at test.pl line 6.
你好吗?
Length: 4

Perl now recognizes the string as a 4-character UTF-8 string, but a warning is issued by Perl, because the output stream (stdout) is not configured to accept UTF-8 decoded strings.

Test 3 - Turn on UTF-8 mode on standard streams
Code:
use utf8;
binmode(*STDOUT, ":utf8");

my $str = "你好吗?";

print("$str\n");
printf("Length: %d\n", length($str));

Now the warning disappears. From the perspective of Perl, UTF-8 is now correctly handled.

But what about strings originated elsewhere (as in your case), rather than embedded in source code? We will need another way.

Test 4 - Use manual decoding
Code:
use Encode;
binmode(*STDOUT, ":utf8");

my $str = "你好吗?";
$str = decode('utf8', $str);

print("$str\n");
printf("Length: %d\n", length($str));

Same result as Test 3, but the decoding is manual. The source code is considered ASCII-encoded, and hence the string literal embedded, but the manual decode allows the decoding of the string literal back to a Perl UTF-8 string, so length() correctly reports the length afterwards.

These examples cover may be 80% of what you will need to know to have Perl process Unicode properly in the majority of cases. For the rest, you will need to consult the manpage.
 

10 More Discussions You Might Find Interesting

1. Programming

Howto convert Ascii -> UTF-8 & back C++

While working with russian text under FreeBSD&MySQL I need to convert a string from MySQL to the Unicode format. I've just started my way in C++ under FreeBSD , so please explain me how can I get ascii code of Char variable and also how can i get a character into variable with the specified ascii... (3 Replies)
Discussion started by: macron
3 Replies

2. Red Hat

Can't convert 7bit ASCII to UTF-8

Hello, I am trying to convert a 7bit ASCII file to UTF-8. I have used iconv before though it can't recognize it for some reason and says unknown file encoding. When I used ascii2uni package with different package, ./ascii2uni -a K -a I -a J -a X test_file > new_test_file It still... (2 Replies)
Discussion started by: rockf1bull
2 Replies

3. Shell Programming and Scripting

How to modify character to UTF-8 in shell script?

I have a shell script running to load some data from a text file to database. Text file contains some non-ASCII characters like ü. How can i convert these characters to UTF-8 codes before loading to DB. (5 Replies)
Discussion started by: vel4ever
5 Replies

4. Shell Programming and Scripting

Convert hex to decimal

can someone help me in converting hex streams to decimal values using perl script Hex value: $my_hex_stream="0c07ac14001676"; Every hex value in the above stream should be converted in to decimal and separated by comma. The output should be: 12,07,172,20,00,22,118 (2 Replies)
Discussion started by: Arun_Linux
2 Replies

5. UNIX for Dummies Questions & Answers

Issue with UTF-8 BOM character in text file

Sometimes we recieve some excel files containing French/Japanese characters over the mail, and these files are manually transferred to the server by using SFTP (security is not a huge concern here). The data is changed to text format before transferring it using Notepad. Problem is: When saving... (4 Replies)
Discussion started by: jawsnnn
4 Replies

6. Linux

Help to Convert file from UNIX UTF-8 to Windows UTF-16

Hi, I have tried to convert a UTF-8 file to windows UTF-16 format file as below from unix machine unix2dos < testing.txt | iconv -f UTF-8 -t UTF-16 > out.txt and i am getting some chinese characters as below which l opened the converted file on windows machine. LANG=en_US.UTF-8... (3 Replies)
Discussion started by: phanidhar6039
3 Replies

7. Shell Programming and Scripting

Trying to convert utf-8 to WINDOWS-1251

Hello all i have utf-8 file that i try to convert to WINDOWS-1251 on linux without any success the file name is utf-8 when i try to do : file -bi test.txt it gives me : text/plain; charset=utf-8 when i try to convert the file i do : /usr/bin/iconv -f UTF-8 -t WINDOWS-1251 test.txt >... (1 Reply)
Discussion started by: umen
1 Replies

8. UNIX for Advanced & Expert Users

UTF-8,16,32 character lengths using awk

Hi All, I am trying to obtain count of characters using awk, but "length" function returns a value of 1 for 2-byte or 3-byte characters as well unlike wc -c command. I have tried to use the below commands within awk function, but it does not seem to work { cmd="wc -c "stringtocheck ( cmd )... (6 Replies)
Discussion started by: tostay2003
6 Replies

9. Shell Programming and Scripting

Convert UTF-8 file to ASCII/ISO8859-1 OR replace characters

I am trying to develop a script which will work on a source UTF-8 file and perform one or more of the following It will accept the target encoding as an argument e.g. US-ASCII or ISO-8859-1, etc 1. It should replace all occurrences of characters outside target character set by " " (space) or... (3 Replies)
Discussion started by: hemkiran.s
3 Replies

10. UNIX for Beginners Questions & Answers

Convert files to UTF-8 on AIX 7.1

Dears, I have a shell script - working perfectly on Oracle Linux - that detects the encoding (the charset to be exact) of the files in a specified directory using the "file" command (The file command outputs the charset in Linux, but doesn't do that in AIX), then if the file isn't a UTF-8 text... (4 Replies)
Discussion started by: JeanM-1
4 Replies
utf8(3pm)						 Perl Programmers Reference Guide						 utf8(3pm)

NAME
utf8 - Perl pragma to enable/disable UTF-8 (or UTF-EBCDIC) in source code SYNOPSIS
use utf8; no utf8; DESCRIPTION
The "use utf8" pragma tells the Perl parser to allow UTF-8 in the program text in the current lexical scope (allow UTF-EBCDIC on EBCDIC based platforms). The "no utf8" pragma tells Perl to switch back to treating the source text as literal bytes in the current lexical scope. This pragma is primarily a compatibility device. Perl versions earlier than 5.6 allowed arbitrary bytes in source code, whereas in future we would like to standardize on the UTF-8 encoding for source text. Until UTF-8 becomes the default format for source text, this pragma should be used to recognize UTF-8 in the source. When UTF-8 becomes the standard source format, this pragma will effectively become a no-op. For convenience in what follows the term UTF-X is used to refer to UTF-8 on ASCII and ISO Latin based platforms and UTF-EBCDIC on EBCDIC based platforms. Enabling the "utf8" pragma has the following effect: o Bytes in the source text that have their high-bit set will be treated as being part of a literal UTF-8 character. This includes most literals such as identifier names, string constants, and constant regular expression patterns. On EBCDIC platforms characters in the Latin 1 character set are treated as being part of a literal UTF-EBCDIC character. Note that if you have bytes with the eighth bit on in your script (for example embedded Latin-1 in your string literals), "use utf8" will be unhappy since the bytes are most probably not well-formed UTF-8. If you want to have such bytes and use utf8, you can disable utf8 until the end the block (or file, if at top level) by "no utf8;". Utility functions The following functions are defined in the "utf8::" package by the perl core. o $num_octets = utf8::upgrade($string); Converts (in-place) internal representation of string to Perl's internal UTF-X form. Returns the number of octets necessary to repre- sent the string as UTF-X. Can be used to make sure that the UTF-8 flag is on, so that "w" or "lc()" work as expected on strings con- taining characters in the range 0x80-0xFF. Note that this should not be used to convert a legacy byte encoding to Unicode: use Encode for that. Affected by the encoding pragma. o utf8::downgrade($string[, FAIL_OK]) Converts (in-place) internal representation of string to be un-encoded bytes. Returns true on success. On failure dies or, if the value of FAIL_OK is true, returns false. Can be used to make sure that the UTF-8 flag is off, e.g. when you want to make sure that the substr() or length() function works with the usually faster byte algorithm. Note that this should not be used to convert Unicode back to a legacy byte encoding: use Encode for that. Not affected by the encoding pragma. o utf8::encode($string) Converts (in-place) $string from logical characters to octet sequence representing it in Perl's UTF-X encoding. Same as Encode::encode_utf8(). Note that this should not be used to convert a legacy byte encoding to Unicode: use Encode for that. o $flag = utf8::decode($string) Attempts to convert $string in-place from Perl's UTF-X encoding into logical characters. Same as Encode::decode_utf8(). Note that this should not be used to convert Unicode back to a legacy byte encoding: use Encode for that. o $flag = utf8::valid(STRING) [INTERNAL] Test whether STRING is in a consistent state. Will return true if string is held as bytes, or is well-formed UTF-8 and has the UTF-8 flag on. Main reason for this routine is to allow Perl's testsuite to check that operations have left strings in a consis- tent state. "utf8::encode" is like "utf8::upgrade", but the UTF8 flag is cleared. See perlunicode for more on the UTF8 flag and the C API functions "sv_utf8_upgrade", "sv_utf8_downgrade", "sv_utf8_encode", and "sv_utf8_decode", which are wrapped by the Perl functions "utf8::upgrade", "utf8::downgrade", "utf8::encode" and "utf8::decode". Note that in the Perl 5.8.0 implementation the functions utf8::valid, utf8::encode, utf8::decode, utf8::upgrade, and utf8::downgrade are always available, without a "require utf8" statement-- this may change in future releases. BUGS
One can have Unicode in identifier names, but not in package/class or subroutine names. While some limited functionality towards this does exist as of Perl 5.8.0, that is more accidental than designed; use of Unicode for the said purposes is unsupported. One reason of this unfinishedness is its (currently) inherent unportability: since both package names and subroutine names may need to be mapped to file and directory names, the Unicode capability of the filesystem becomes important-- and there unfortunately aren't portable answers. SEE ALSO
perlunicode, bytes perl v5.8.0 2002-06-01 utf8(3pm)
All times are GMT -4. The time now is 10:13 PM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy