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

trying to convert hex to ascii and was able to convert. Any idea code can be written more efficiently. Please preview.

my $x = 30:30:3a:31:64:3a:69:2d:6f; #in hex my $x =~ tr/://d; my $y = hex_to_ascii("$x"); print "$y\n"; #in ascii

Above can be achieved using one liner? Tried using pack and unpack and closest i can think of was split, conversion and pack. Preview and guide how to correct. Thanks!

my $y = pack ('C*', split/\:/, $x);

Replies are listed 'Best First'.
Re: Perl Hex ASCII pack unpack
by ikegami (Patriarch) on Sep 26, 2014 at 05:21 UTC

    I presume you're asking how to get the string of 9 bytes that string represents.

    $x =~ tr/://d; my $y = pack('H*', $x);
    my $y = pack('H*', $x =~ tr/://dr); # 5.14+ required
    (my $y = $x) =~ s/([0-9a-fA-F]{2}):?/chr(hex($1))/eg;
    my $y = $x =~ s/([0-9a-fA-F]{2}):?/chr(hex($1))/egr; # 5.14+ required
    my $y = pack 'C*', map hex, split /:/, $x;
    my $y = join '', map chr hex, split /:/, $x;

      Thanks

Re: Perl Hex ASCII pack unpack
by Anonymous Monk on Sep 26, 2014 at 07:38 UTC

    clean your room :)

    my $x = 30:30:3a:31:64:3a:69:2d:6f; #in hex Bareword found where operator expected at - line 1, near "3a" (Missing operator before a?) Bareword found where operator expected at - line 1, near "3a" (Missing operator before a?) Bareword found where operator expected at - line 1, near "2d" (Missing operator before d?) Bareword found where operator expected at - line 1, near "6f" (Missing operator before f?) __END__ syntax error at - line 1, near "30:" Execution of - aborted due to compilation errors.