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

I read perlfunc and all it has to say on the subject is:
'p' A pointer to a null-terminated string.
'P' A pointer to a structure (fixed-length string).

I tried using this to read the contents of a reference but all I get is fatal exceptions. How is this used in practice?

Sample code:

use B 'svref_2object'; $rv = \"hello kitty"; $rv_obj = svref_2object( $rv ); $rv_address = B::address( $rv_obj ); $sv_any = unpack 'P4', $rv_address; # It fails here $rv_address += 4; $sv_refcnt = unpack 'P4', $rv_address; # or here if I just increment t +he address $rv_address += 4; $sv_flags = unpack 'P4', $rv_address; # or anywhere I try using unpack + 'P' printf "%08x\n%08x\n%08x\n", $sv_refcnt;

So what do I have to do to get P to work? I'd like to be able to do some runtime magic but this has me stymied.

Replies are listed 'Best First'.
Re: Using pack with P and p?
by sauoq (Abbot) on Sep 23, 2002 at 22:23 UTC

    Here's some example code that might help you understand.

    #!/usr/bin/perl $x ="somestringyoulike"; $y = pack("p", $x); # Null terminated $z = pack("P",$x); # Fixed length print '$x length : ', length($x), "\n"; print '$y length : ', length($y), " (it's a pointer.)\n"; print '$z length : ', length($y), " (it's a pointer.)\n"; print 'unpack $y : ', unpack("p",$y), "\n"; $x = "a new string"; print 'unpack $y : ', unpack("p",$y), "\n"; # $y still points to $ +x print '$z 1 byte : ', unpack("P",$z), "\n"; # The first byte of $ +z print '$z 4 bytes: ', unpack("P4",$z), "\n"; # The first 4 bytes. print '$z 17 bytes: ', unpack("P17",$z), "\n"; # The whole 17 bytes. # Remember that $y is null terminated... so there must be # a null in the string when we unpack 17 bytes of $z # because they point to the same thing. This finds that null... $s = unpack("P17", $z); $s =~ /(.)\0(.)/; print '\0 between: ', "$1 and $2\n";
    -sauoq
    "My two cents aren't worth a dime.";
    

      I see... I've misunderstood what the 'p' format does. Using pack('p',$something) will give me a pointer to something in memory and unpack('p',$address) reads from the pointer. I had been expecting that pack() would write to some address though on consideration that doesn't make sense since there isn't another field available to use for the data (unless pack were an lvalue). Hmm... ok. So is there a way to write to memory in perl-space? I'd really like to be able to muck with the internals without just including an XS writeMemory() method.

Re: Using pack with P and p?
by diotalevi (Canon) on Sep 23, 2002 at 21:45 UTC

    I suppose I should mention that I did try searching but it's dog all difficult to find anything on this since the magic bit is in that one parameter - it's not keywordly if you know what I mean.