How does Perl store integers in memory?

say pack "A*", "asdf";           # Prints "asdf"
say pack "s", 0x41 * 256 + 0x42; # Prints "BA" (0x41 = 'A', 0x42 = 'B')

The first line makes sense: you take an ASCII encoded string, inserting it into the string as an ASCII string. The second line contains the packed form "\ x42 \ x41" due to the small finiteness of short integers on my machine.

However, I can’t shake the feeling that somehow I have to be able to treat the packed line from the second line as a number, since this, as I assume, Perl stores numbers, since the sequence of bytes is of lower order, Is there a way to do this without it unpacking? I am trying to get the right mental model for what pack () returns.

For example, in C, I can do this:

#include <stdio.h>

int main(void) {
    char c[2];
    short * x = c;
    c[0] = 0x42;
    c[1] = 0x41;

    printf("%d\n", *x); // Prints 16706 == 0x41 * 256 + 0x42
    return 0;
}
+4
source share
3 answers

pack . Perl . , Perl, , .

, , , , , , .

, vec:

say vec "BA", 0, 16;  # prints 16961

, Devel:: Peek, - ASCII.

use Devel::Peek;
Dump "BA";

SV = PV(0xb42f80) at 0xb56300
  REFCNT = 1
  FLAGS = (POK,READONLY,pPOK)
  PV = 0xb60cc0 "BA"\0
  CUR = 2
  LEN = 16
+2

, Perl , PerlGuts Illustrated. , , , Perl . , XS C.

"" C short, unpack :

$ perl -le 'print unpack("s", "BA")'
16706
+4

, - ,

.

  • C,

    char* packed = "\x42\x41";
    int16_t int16;
    memcpy(&int16, packed, sizeof(int16_t));
    
  • Perl,

    my $packed = "\x42\x41";
    my $num = unpack('s', $packed);
    

    use Inline C => <<'__EOI__';
    
       SV* unpack_s(SV* sv) {
          STRLEN len;
          char* buf;
          int16_t int16;
    
          SvGETMAGIC(sv);
          buf = SvPVbyte(sv, len);
          if (len != sizeof(int16_t))
             croak("usage");
    
          Copy(buf, &int16, 1, int16_t);
          return newSViv(int16);
       }
    
    __EOI__
    
    my $packed = "\x42\x41";
    my $num = unpack_s($packed);
    

, , perl , .

Perl :

  • IV, perl -V:ivsize ( ).
  • UV, perl -V:uvsize ( ). (Ivsize = uvsize)
  • NV, perl -V:nvsize ( ).

In all cases, the native specification is used.

I am trying to get the right mental model for what pack () returns.

pack used to create "binary data" for interacting with external APIs.

+3
source

All Articles