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

Hi Monks

I am stuck a piece of pie. I am trying to convert a hex string into ASCII characters and can't seem to find my way out.

while(<DATA>) { $flag = 0; $line = $_; $line =~ s/\s//g; send(SOCKET, $line, $flag); } __DATA__ 41 42 43 44 45 46 47 48 49 # ASCII: A B C D E F G H I

My problem here is I want to have "41" converted to "A" before being send. However, my current code is sending the characters 4 1 ... and so on as individual charaters. Could any monk kindly help me solve this problem?

Thanks

Replies are listed 'Best First'.
Re: Converting Hex String ASCII Char
by pc88mxer (Vicar) on Apr 30, 2008 at 17:15 UTC
    use pack with the H format:
    my $bytes = pack("H*", $line);
Re: Converting Hex String ASCII Char
by kyle (Abbot) on Apr 30, 2008 at 17:27 UTC

    Since I'm not too familiar with pack, I'd do it this way:

    my $out = join '', map { chr hex } split /\s+/, $line;
Re: Converting Hex String ASCII Char
by tuxz0r (Pilgrim) on Apr 30, 2008 at 17:30 UTC
    You could try another search/replace using the built in chr() and hex() routines:
    echo "41 42 43 44 45 46 47 48 49" | perl -ape 's/([0-9a-f]+)/chr(hex($ +1))/eg;'
    Which should give you "A B C D E F G H I".

    * - modified the regex based on kyles observation (good catch)

    ---
    s;;:<).>|\;\;_>?\\^0<|=!]=,|{\$/.'>|<?.|/"&?=#!>%\$|#/\$%{};;y;,'} -/:-@[-`{-};,'}`-{/" -;;s;;$_;see;
    Warning: Any code posted by tuxz0r is untested, unless otherwise stated, and is used at your own risk.

      Since the OP is actually matching hex, the \d pattern won't work. You'll need to use [0-9a-f] instead.

        good catch kyle, I kind of whipped that one off the cuff just using his data. Thanks.

        ---
        s;;:<).>|\;\;_>?\\^0<|=!]=,|{\$/.'>|<?.|/"&?=#!>%\$|#/\$%{};;y;,'} -/:-@[-`{-};,'}`-{/" -;;s;;$_;see;
        Warning: Any code posted by tuxz0r is untested, unless otherwise stated, and is used at your own risk.