August 2011 Archives

DC.pm August 2011 Meeting - Devel::Peek

Last Tuesday was our monthly DC Perl Mongers meeting.

We dove right in, talking about how perl caches various values for a variable to be used in different contexts. So, for example, let's say you start off with a number, but then use it in string context, perl will cache both the string and the number. This can be shown using Devel::Peek like this:

main:001:0> use Devel::Peek
main:002:0> my $x = "34"
34
main:003:0> Dump($x)
SV = PV(0xb22d558) at 0xb237290
  REFCNT = 2
  FLAGS = (POK,pPOK)
  PV = 0xb249458 "34"\0
  CUR = 2
  LEN = 4


I often use Devel::REPL at meetings so that we can interactively explore things as a group, which is what I'm doing here.

The first time we dump $x, you can see it has a "PV" which holds the string "34". But after we use it in a number context, adding 17 to it, you can see that the dump shows both the original string version, and a new "IV" containing the integer version:

main:004:0> $x + 17
51
main:005:0> Dump($x)
SV = PVIV(0xa0fe6b8) at 0xb237290
  REFCNT = 2
  FLAGS = (IOK,POK,pIOK,pPOK)
  IV = 34
  PV = 0xb249458 "34"\0
  CUR = 2
  LEN = 4


So this, as far as I know, is mainly an efficiency hack that perl does, the theory being that if you used it once in string context or number context or whatever, maybe you'll do it again.

Very quickly the question came up as to what happens when you change $x, and how does perl know what cached values to trust. Well that's where the 'FLAGS' part of the SV dump comes in. It shows which of the cached values are OK to use. So when we increment $x numerically:

main:006:0> $x++
34
main:007:0> Dump($x)
SV = PVIV(0xa0fe6b8) at 0xb237290
  REFCNT = 2
  FLAGS = (IOK,pIOK)
  IV = 35
  PV = 0xb249458 "34"\0
  CUR = 2
  LEN = 4


The flags have been trimmed down. I don't remember what all the flags mean, but you can look at perlguts or other docs for that :) . Notice that the string version of the original "34" is still there! Perl doesn't waste time erasing it. Instead, if string context is used again a new cached value will overwrite the existing one.

Well that was surely a good start to the meeting :)

(Cross-posted from thelackthereof.org)

About awwaiid (Brock Wilcox)

user-pic Software Inventor