2011.08.07 DC Perl Mongers August 2011 Meeting

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"
main:003:0> Dump($x)
SV = PV(0xb22d558) at 0xb237290
  REFCNT = 2
  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
main:005:0> Dump($x)
SV = PVIV(0xa0fe6b8) at 0xb237290
  REFCNT = 2
  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++
main:007:0> Dump($x)
SV = PVIV(0xa0fe6b8) at 0xb237290
  REFCNT = 2
  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 :)


Blog Blog RSS Feed






Toots (Mastodon)




Follow @awwaiid

Wiki Edits Wiki RSS Feed

... more changes