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

Take a look at the following code:
$text_a = "\xca\xc0\xbd\xe7\xc3\xb3\xd2\xd7\xd7\xe9\xd6\xaf\x0a"; print $text_a; $text_b = "cac0bde7c3b3d2d7d7e9d6af0a";
$text_a contains some Chinese GB2312 encoded string. What I wanna know is how to convert the hex style string like $text_b to the encoded literal string $text_a. I've heard it's hard to manipulate bytes and characters in perl. I badly need your help. Thanks a lot :)

Replies are listed 'Best First'.
Re: How to convert hex string to real string ?
by jmcnamara (Monsignor) on Feb 17, 2003 at 09:29 UTC

    You can do it like this:
    $text_a = pack "H*", $text_b; # and to convert back: $text_b = unpack "H*", $text_a;

    --
    John.

Re: How to convert hex string to real string ?
by grantm (Parson) on Feb 17, 2003 at 09:29 UTC

    How about:

    $text_b = pack('H*', "cac0bde7c3b3d2d7d7e9d6af0a");
Re: How to convert hex string to real string ?
by hardburn (Abbot) on Feb 17, 2003 at 15:05 UTC

    I've heard it's hard to manipulate bytes and characters in perl.

    No, it's really easy, but you have to understand the workings of regexen, pack(), unpack(), and a few others in order to do it. Learning is hard, but once you finally "get it", munging data in Perl is easy.

    ----
    Invent a rounder wheel.

Re: How to convert hex string to real string ?
by robartes (Priest) on Feb 17, 2003 at 09:30 UTC
    This seems like a straightforward regex job:
    my $text_b="cac0bde7c3b3d2d7d7e9d6af0a"; $text_b=~s/([0-9a-f]{2})/\\x\1/g; print $text_b; __END__ \xca\xc0\xbd\xe7\xc3\xb3\xd2\xd7\xd7\xe9\xd6\xaf\x0a
    Update: Oops - seems I misunderstood the meaning of "encoded literal string". Never mind my rambling (or downvote it :-) ) - pack as above is the solution.

    CU
    Robartes-