in reply to Differences in behavior in pack

For the first conversion, you want printf/sprintf, not unpack (and there's no telling how many zeroes you originally padded the number with):
$testp = 0x007102; printf ("Hex 0x%x\n", $testp);

Replies are listed 'Best First'.
Re^2: Differences in behavior in pack
by sxmwb (Pilgrim) on Apr 09, 2008 at 00:48 UTC
    Ok, so I guess to ask a better question?

    What is the difference in the way Perl stores these values? Is there away to tell the difference from a programmatic viewpoint if I am expecting hex values? What happens if the values are passed to my program either way?

    $testp = 0x007102; $testp1 = "\x30\x05\x15";
    Thanks again,
    Mike

      Technically, it's possible to tell the difference

      >perl -MDevel::Peek; -e"Dump(0x007102)" SV = IV(0x18265fc) at 0x2252f8 REFCNT = 1 FLAGS = (PADBUSY,PADTMP,IOK,READONLY,pIOK) IV = 28930 >perl -MDevel::Peek; -e"Dump(qq{\x30\x05\x15})" SV = PV(0x226680) at 0x225300 REFCNT = 1 FLAGS = (PADBUSY,PADTMP,POK,READONLY,pPOK) <-- Not IOK/UOK/NOK PV = 0x182f6a4 "0\5\25"\0 CUR = 3 LEN = 4

      But checking for that would be extremely fragile. I strongly recommend against that approach. Instead, use some kind of meta data (a different command line switch, for example) to specify the format, then canonize it for internal use.

      # Inputs my $input = "\x30\x05\x15"; my $packed = 1; # Canonize input if ($packed) { $input = unpack('N', substr(("\x00"x4).$input, -4)); } # Do some work #... # Output results printf("Results for 0x%X are %s\n", $input, "...");

      Update: Added second snippet.