in reply to Using pack with P and p?

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.";

Replies are listed 'Best First'.
Re: Re: Using pack with P and p?
by diotalevi (Canon) on Sep 24, 2002 at 00:56 UTC

    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.