in reply to Convert to Hexadecimal

unpack or sprintf to get the hex digits. The substitution operator to match the hex digits, prepending each pair with the literal '\x'.

my $string = "39860000N000"; my $hexlen = sprintf( '%4.4x', length $string ) =~ s/ ( \p{Hex}{2} ) / +\\x$1/grx; print "Length of ($string) in hex: ($hexlen)\n";

In older versions of Perl that didn't have the /r flag you would probably want to break that into a couple of statements (and may still wish to do so for clarity's sake):

my $string = '39860000N000'; my $hexlen = sprintf '%4.4x', length $string; $hexlen =~ s/ ( \p{Hex}{2} ) /\\x$1/gx; print "Length of ($string) in hex: ($hexlen)\n";

Dave

Replies are listed 'Best First'.
Re^2: Convert to Hexadecimal
by sauoq (Abbot) on May 17, 2012 at 19:07 UTC

    $hexlen = printf("\\x%02x\\x%02x", unpack("C2", pack("n", length($string)));

    (Explanation in reply to OP.)

    -sauoq
    "My two cents aren't worth a dime.";
Re^2: Convert to Hexadecimal
by martydavis (Initiate) on May 17, 2012 at 18:53 UTC
    Forever grateful!

    Works like a charm. It will take me some time to understand it though.